blob: 802cb51335a11e4f511cc10321baaf6cc4aaeee9 (
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
|
#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()
{
shared_ptr<Test> smart_pointer_1(new Test());
cout << smart_pointer_1.get() << endl; //адресът на обекта.
weak_ptr<Test> smart_pointer_2(smart_pointer_1);
cout << smart_pointer_2.use_count() << endl; // 1 - weak_ptr НЕ участва в бройката на пойнтерите към обектите.
//smart_pointer_2->f(); ГРЕШКА!
//Това е само за временен достъп! Ако искате да достъпите данните на този пойнтер трябва да го превърнете в shared_ptr!.
shared_ptr<Test> smart_pointer_3 = smart_pointer_2.lock();
cout << smart_pointer_1.use_count() << endl;//2
smart_pointer_3->f(); // .. и тн.
}
|