-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_Smart-pointers.cpp
More file actions
47 lines (38 loc) · 777 Bytes
/
2_Smart-pointers.cpp
File metadata and controls
47 lines (38 loc) · 777 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>
class StringPointer {
private:
std::string *ptr_;
public:
std::string *operator->()
{
if (!this->ptr_)
this->ptr_ = new std::string();
return this->ptr_;
}
operator std::string*()
{
if (!this->ptr_)
this->ptr_ = new std::string();
return this->ptr_;
}
StringPointer(std::string *Pointer)
: ptr_(Pointer)
{}
~StringPointer()
{
if (this->ptr_)
delete this->ptr_;
}
}; //!class StringPointer
// main test
int main()
{
StringPointer sp1(new std::string("Hello, world!"));
StringPointer sp2(NULL);
std::cout << sp1->length() << std::endl;
std::cout << *sp1 << std::endl;
std::cout << sp2->length() << std::endl;
std::cout << *sp2 << std::endl;
return 0;
}