forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex13_27.h
48 lines (43 loc) · 886 Bytes
/
ex13_27.h
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
//
// ex13_27.h
// Exercise 13.27
//
// Created by pezy on 1/20/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Define your own reference-counted version of HasPtr.
#ifndef CP5_ex13_27_h
#define CP5_ex13_27_h
#include <string>
class HasPtr {
public:
HasPtr(const std::string& s = std::string())
: ps(new std::string(s)), i(0), use(new size_t(1))
{
}
HasPtr(const HasPtr& hp) : ps(hp.ps), i(hp.i), use(hp.use) { ++*use; }
HasPtr& operator=(const HasPtr& rhs)
{
++*rhs.use;
if (--*use == 0) {
delete ps;
delete use;
}
ps = rhs.ps;
i = rhs.i;
use = rhs.use;
return *this;
}
~HasPtr()
{
if (--*use == 0) {
delete ps;
delete use;
}
}
private:
std::string* ps;
int i;
size_t* use;
};
#endif