Website Summary Files Commits Branches @commit @diff @stats
path: root / Smart_pointers / 2. shared_ptr.cpp
blob: 4ac5d517c8940405503efb20b27a3e6dc0ec5a14 (plain) (blame)
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


#include <iostream>
#include <memory> 

using namespace std;

class Test
{
public:
	Test()
	{
		cout << "Test()" << endl;
	}
	Test(const Test& other)
	{
		cout << "Copy constructor" << endl;
	}
	Test& operator=(const Test& other)
	{
		cout << "Assignment operator" << endl;
	}
	~Test()
	{
		cout << "Detructor" << endl;
	}

};
int main()
{


	shared_ptr<Test> smart_pointer_1(new Test());

	cout << smart_pointer_1.get() << endl; //адресът на обекта.

	shared_ptr<Test> smart_pointer_2(smart_pointer_1);

	cout << smart_pointer_1.get() << endl; //За разлика от uniqe_ptr тук smart_pointer_1 ПРОДЪЛЖАВА да сочи към обекта.  

	cout << smart_pointer_2.use_count() << endl; //може да видим колко пойнтера са насочени към обекта.
	// Обектът ще се изтрие, когато пойнтерите станат 0.


	{
		shared_ptr<Test> smart_pointer_3 = smart_pointer_2;

		cout << smart_pointer_1.use_count() << endl; //3 пойнтера към обекта ни.

	}
	cout << smart_pointer_1.use_count() << endl; // 2, защото smart_pointer_3 вече го няма.

	return 0;
} //тук изчезват пойнтерите -> броят им става 0 и обекта се изтрива(изтрива се от последния пойнтер преди да изчезне)
//Възможно е да се получи цикличност. Един shared_ptr да реферира друг shared_ptr, който обратно да реферира първия!