shared_ptr
Common interface
use_count() : Get reference count number .
get() : Get the original pointer .
reset() : point NULL Memory .
matters needing attention
1. Cannot assign values directly NULL, Compilation failed ; If you need to empty it reset();reset after ,ptr point NULL Memory .
2. Memory cannot be released manually , as delete ptr.get(), This will cause a memory error , As for why , It's not clear .
3. Allocate memory first , Then give it to the smart pointer , No more release , as
int * c = new int;
boost::shared_ptr<int> pObj(c);
delete c;
A memory error will occur ,boost How to prevent users from being outside delete c What about ?
weak_ptr
Is a smart pointer to execute a weak reference . When you need it, you can use a strong ( share ) The pointer points to it ( When the object is released , It is empty ), Of course, this strong pointer should be released immediately after use
struct CBetterChild : public CSample { weak_ptr<CDad> myDad; void BringBeer()
{ shared_ptr<CDad> strongDad = myDad.lock(); // request a strong pointer if
(strongDad) // is the object still alive? strongDad->SetBeer(); // strongDad is
released when it goes out of scope. // the object retains the weak pointer } };
matters needing attention
1. Weak references if you need to manipulate class objects , Need to be converted to a strong reference , adopt lock Interface acquisition
2. After obtaining a strong reference , It is necessary to detect whether the object is empty , Because it is possible that the object has been released
3. After operation , Strong references should be released immediately , In other words, strong references are best temporary local variables
Common interface
lock() : Turn to strong reference , If the object has been released , Returns a null strong reference
expired(): Determine whether the object has been released
Technology
Daily Recommendation