-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringpointer.cpp
More file actions
61 lines (53 loc) · 1.35 KB
/
stringpointer.cpp
File metadata and controls
61 lines (53 loc) · 1.35 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
#include <iostream>
#include <string>
class StringPointer
{
public:
StringPointer(std::string* ptr): ptr(ptr), raw(false) {}
std::string* operator->()
{
checkPtr();
return ptr;
}
std::string operator*()
{
checkPtr();
return *ptr;
}
operator std::string*()
{
checkPtr();
return ptr;
}
~StringPointer()
{
if(raw)
{
delete ptr;
}
}
private:
void checkPtr()
{
if(ptr == NULL)
{
raw = true;
ptr = new std::string();
}
}
std::string* ptr;
bool raw;
};
int main()
{
std::string s1 = "Hello, world";
StringPointer sp1(&s1);
StringPointer sp2(NULL);
std::cout << "sp1->length(): " << sp1->length() << std::endl;
std::cout << "*sp1: " << *sp1 << std::endl;
std::cout << "sp2->length: " << sp2->length() << std::endl;
std::cout << "*sp2: " << (*sp2).length() << std::endl;
return 0;
}