forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex13.27.cpp
81 lines (60 loc) · 1.29 KB
/
ex13.27.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 01 JAN 2014
* @remark
***************************************************************************/
//!
//! Exercise 13.27:
//! Define your own reference-counted version of HasPtr.
//!
#include <string>
#include <iostream>
//! for ex13.27
class HasPtr
{
public:
//! default constructor.
HasPtr(const std::string &s = std::string()):
ps(new std::string(s)), i(0), useCounter(new std::size_t(1)) { }
//! copy constructor.
HasPtr(const HasPtr& rhs) : ps(rhs.ps), i(rhs.i), useCounter(rhs.useCounter)
{
++*useCounter;
}
HasPtr&
operator = (const HasPtr& rhs);
~HasPtr()
{
if(--*useCounter == 0)
{
delete ps;
delete useCounter;
}
}
private:
std::string* ps;
int i;
std::size_t* useCounter;
};
int main()
{
HasPtr hp("aaaaaa"), hp2;
HasPtr hp1(hp);
hp2 = hp1;
return 0;
}
inline HasPtr&
HasPtr::operator =(const HasPtr &rhs)
{
++*rhs.useCounter;
if(--*useCounter == 0)
{
delete useCounter;
delete ps;
}
ps = rhs.ps;
useCounter = rhs.useCounter;
i = rhs.i;
return *this;
}