forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex13_30.h
50 lines (44 loc) · 1.06 KB
/
ex13_30.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
49
50
//
// ex13_30.h
// Exercise 13.30
//
// Created by pezy on 1/23/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Write and test a swap function for your valuelike version of HasPtr.
// Give your swap a print statement that notes when it is executed.
//
// See ex13_22.h
#ifndef CP5_ex13_11_h
#define CP5_ex13_11_h
#include <string>
#include <iostream>
class HasPtr {
public:
friend void swap(HasPtr&, HasPtr&);
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; }
void show() { std::cout << *ps << std::endl; }
private:
std::string* ps;
int i;
};
void swap(HasPtr& lhs, HasPtr& rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
std::cout << "call swap(HasPtr& lhs, HasPtr& rhs)" << std::endl;
}
#endif