forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex13_22.h
44 lines (40 loc) · 1.04 KB
/
ex13_22.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
//
// ex13_22.h
// Exercise 13.22
//
// Created by pezy on 1/13/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Assume that we want HasPtr to behave like a value.
// That is, each object should have its own copy of the string to which the
// objects point.
// We¡¯ll show the definitions of the copy-control members in the next section.
// However, you already know everything you need to know to implement these
// members.
// Write the HasPtr copy constructor and copyassignment operator before reading
// on.
//
// See ex13_11.h
#ifndef CP5_ex13_11_h
#define CP5_ex13_11_h
#include <string>
class HasPtr {
public:
HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0)
{
}
HasPtr(const HasPtr& hp) : ps(new std::string(*hp.ps)), i(hp.i) {}
HasPtr& operator=(const HasPtr& hp)
{
auto new_p = new std::string(*hp.ps);
delete ps;
ps = new_p;
i = hp.i;
return *this;
}
~HasPtr() { delete ps; }
private:
std::string* ps;
int i;
};
#endif