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
©2019-2020 Toolsou All rights reserved,
Send love - A little romance for programmers VHDL—— Design of frequency divider Python Implementation of Hanoi Tower code It's over , Starting salary 30khtml+css+js Make a simple website home page QQ Login interface implementation Hill sorting of sorting algorithm ——c++ realization 【 Wechat applet learning 】 Netease music cloud code page implementation details Resume the 13th session python Blue Bridge Cup 2022 Solution to the 13th Blue Bridge Cup ( whole )