Website Summary Files Commits Branches @commit @diff @stats
path: root / Smart_pointers / 1. uniqe_ptr.cpp
blob: 1b2f9eb9aeda1d85a4f045ac7f9f51c3356c0d95 (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
56
#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;
  }
  void f()
  {

  }
    
};
int main()
{
	{
		unique_ptr<Test> smart_pointer_1(new Test()); //Test()
		
		smart_pointer_1->f(); // Достъпваме данните, както с обикновен пойнтер.
		
		Test* obj = smart_pointer_1.get(); //От тук иматаме достъп до паметта, към която сочи пойнтера.
		//delete obj; // Това не трябва да се прави! smart_pointer_1 не знае, че паметта е освободена и ще се опита да я освободи, което ще доведе до грешка!

	}  //Test  (Паметта се освобождава сама)

	{
		
		unique_ptr<Test> smart_pointer_2(new Test());

       	 	unique_ptr<Test> smart_pointer_3 = move(smart_pointer_2);
		// unique_ptr<Test> smart_pointer_3(smart_pointer_2); //този синтаксис (както и оператор =) не е валиден! Те бяха валидни в стария и не толкова иползван auto_ptr.

		smart_pointer_2.get(); // Това ще даде NULL, защото smart_pointer_3 "открадна" обекта на smart_pointer_2 
		
	}
    
    
    return 0;
}