forked from nesteruk/ModernCpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SmartPointers.cpp
78 lines (64 loc) · 1.18 KB
/
SmartPointers.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
#include "Headers.h"
class Address
{
public:
Address() {}
Address(const Address&) { cout << "Address copied!" << endl; }
int house_number;
string street;
string city;
string postcode;
};
Address create_address(int house, string postcode)
{
Address address{};
address.house_number=house;
address.postcode = postcode;
// fill other fields
return address; // rvo?
}
unique_ptr<Address> create_address_smart(int house, string postcode)
{
auto a = make_unique<Address>();
return a;
}
//class Person
//{
//public:
// Address* address;
// Person() { address = new Address(); }
// ~Person() { delete address; }
//};
class Person {
public:
unique_ptr<Address> address;
Person()
{
address = make_unique<Address>();
}
~Person()
{
cout << "Person destroyed" << endl;
}
};
int main()
{
cout << "Smart pointer test!" << endl;
auto my_address = create_address(32, "SO171BJ");
auto my_address2 = create_address_smart(32, "SO171BJ");
// Address* a;
// {
// Person p;
// a = p.address;
// }
// cout << a->city << endl;
unique_ptr<Address> a;
{
Person p;
p.address->city = "London";
//a = p.address; // on unique_ptr will not work
}
cout << a->city;
getchar();
return 0;
}