C + + Smart pointer learning

Source: Internet
Author: User

C + + Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21st
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
SmartPtr.cpp
Author:michael Joessy
date:2017-06-07
Marks:c++ four smart pointers inside: auto_ptr, shared_ptr, weak_ptr, unique_ptr;
The latter three are c++11 supported, and the first one has been deprecated by c++11.

Why Use smart pointers:
We know that C + + memory management is a headache for a lot of people, when we write a new statement, the general will immediately write the DELETE statement directly;
But we can not avoid the program has not executed to delete when the jump or in the function is not executed to the last DELETE statement is returned;
If we do not release resources before every possible jump or return statement, we will cause a memory leak.
Using smart pointers can largely avoid this problem:
Because a smart pointer is a class, when the scope of the class is exceeded, the class automatically calls the destructor, and the destructor automatically frees the resource.
*/


#include<memory>
#include<iostream>
#include<string>

using namespacestd;
using namespacestd::tr1;

Auto_ptr http://www.cplusplus.com/reference/memory/auto_ptr/
Unique_ptr http://www.cplusplus.com/reference/memory/unique_ptr/
Share_ptr http://www.cplusplus.com/reference/memory/share_ptr/
Weak_ptr http://www.cplusplus.com/reference/memory/weak_ptr/
classtestsmartptr
{
Public:
Testsmartptr (String str)
{
m_str = str;
cout <<
"Testsmartptr creat\n";
}
~testsmartptr ()
{
cout <<
"testsmartptr Delete:"<< m_str <<endl;
}
string& Getstr ()
{
returnm_str;
}
voidSETSTR (String str)
{
m_str = str;
}
voidprint ()
{
cout << m_str << Endl;
}
Private:
String m_str;
};


classClassB;
classClassA
{
Public:
//shared_ptr<classb> pb_;
weak_ptr<classb> pb_;
~classa ()
{
cout <<
"ClassA delete\n";
}
};
classClassB
{
Public:
Shared_ptr<classa> Pa_;
~CLASSB ()
{
cout <<
"ClassB delete\n";
}
};


intMain (void)
{
//auto_ptr
    The/* member function get () returns an original pointer to the member function reset () to rebind the object to, and the original object is freed
Determine if a smart pointer is empty should use if (ptestautoptr.get () = = null)
The member function release () simply assigns the smart pointer to null, but the memory it originally points to is not released, which is equivalent to releasing the ownership of the resource
We can use Ptestautoptr.reset () when we want to release resources halfway through, rather than wait until the smart pointer is destroyed; Statement.
*/

#if 0
Auto_ptr<testsmartptr> Ptestautoptr (
NewTestsmartptr ("315"));
if(ptestautoptr.get () = =NULL)
{
cout <<
"ptestautoptr = null\n";
}
Ptestautoptr->setstr (
"Michael");
Ptestautoptr->print ();
Ptestautoptr.get ()->print ();
PTESTAUTOPTR->GETSTR () + =
"Joessy!";
(*ptestautoptr). print ();
Ptestautoptr.reset (
NewTestsmartptr ("315"));
Ptestautoptr->print ();
Ptestautoptr.release ();
#endif
//unique_ptr
    /*UNIQUE_PTR is a proprietary smart pointer that provides a strict sense of ownership, including:
1. Have the object it points to
2, unable to copy the construction, can not copy assignment operation. That is, you cannot point two unique_ptr to the same object. However, you can move the construction and move assignment operations
3. A pointer to an object is saved, and when it is deleted, it releases the object it points to with the given delete.
Unique_ptr can achieve the following functions:
1. Provide exception security for dynamically applied memory
2, dynamic application of memory ownership passed to a function
3. Return the ownership of dynamic request memory from a function
4. Save the pointer in the container
5, auto_ptr should have the function
*/

#if 0
unique_ptr<
int> Up (P);
Unique_ptr<testsmartptr> PTestUniquePtr1 (
NewTestsmartptr ("123"));
Unique_ptr<testsmartptr> PTESTUNIQUEPTR2 (
NewTestsmartptr ("456"));
Ptestuniqueptr1->print ();
PTESTUNIQUEPTR2 = Std::move (PTESTUNIQUEPTR1);
//cannot be directly pTestUniquePtr2 = PTESTUNIQUEPTR1
    if(pTestUniquePtr1 = =NULL)
{
cout <<
"PTESTUNIQUEPTR1 = null\n";
}
testsmartptr* p = ptestuniqueptr2.release ();
P->print ();
Ptestuniqueptr1.reset (P);
Ptestuniqueptr1->print ();
#endif
Share_ptr
    / * from share you can see that resources can be shared by multiple pointers, using a counting mechanism to indicate that resources are shared by several pointers.
You can view the number of owners of a resource by using the member function Use_count ().
In addition to being constructed through new, it can be constructed by passing in Auto_ptr, Unique_ptr,weak_ptr.
When we call Release (), the current pointer frees the resource ownership, and the count is reduced by one.
When the count equals 0 o'clock, the resource is freed.
*/

#if 0
Shared_ptr<testsmartptr> PTestSharePtr1 (
NewTestsmartptr ("123"));
Shared_ptr<testsmartptr> PTESTSHAREPTR2 (
NewTestsmartptr ("456"));
cout << ptestshareptr2->getstr () <<endl;
cout << ptestshareptr2.use_count () <<endl;
PTESTSHAREPTR1 = PTESTSHAREPTR2;
//"456" citation count plus 1, "123" destroyed
Ptestshareptr1->print ();
cout << ptestshareptr2.use_count () << Endl;
cout << ptestshareptr1.use_count () << Endl;
Ptestshareptr1.reset ();
Ptestshareptr2.reset ();
//At this time "456" destroyed
#endif
//weak_ptr
    /*weak_ptr is used to solve the deadlock problem when shared_ptr mutual reference;
If two shared_ptr refer to each other, then the reference count of the two pointers will never be dropped to 0, and the resource will never be freed.
It is a weak reference to the object, does not increase the object's reference count, and shared_ptr can be converted to each other;
SHARED_PTR can be assigned directly to it, which can be obtained by calling the lock function to get shared_ptr.
*/

#if 0
Shared_ptr<classb> PB (
NewClassB ());
Shared_ptr<classa> PA (
NewClassA ());
Pb->pa_ = PA;
Pa->pb_ = PB;
cout << pb.use_count () << Endl;
cout << pa.use_count () << Endl;
#endif
/* Description:
The PA and PB reference each other, the reference count of two resources is 2;
When you want to jump out of a function, the two resource reference counts will be reduced by a smart pointer pa and PB destruction.
However, the reference count is still 1, which causes the resource to not be released when the function jumps out (ClassA and CLASSB destructors are not called).

If we change one of them to weak_ptr, we put the shared_ptr<b> pb_ in Class A; instead of weak_ptr<b> pb_;
In this case, the reference to resource CLASSB begins with only 1;
When PB is reconstructed, the count of B becomes 0,b released;
b Releasing also makes a count minus one;
At the same time, when the PA is refactored, the count of a is reduced by one, then the count of A is 0,a released.
*/



Cin.get ();
return 0;
}

C + + Smart pointer learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.