C ++ 11 Study Notes-smart pointer

Source: Internet
Author: User

C ++ 11 Study Notes-smart pointer
Std: auto_ptr of C ++ 98 has been completely abandoned and replaced by unique_ptr, shared_ptr, and weak_ptr. Most of the time, we manually apply for memory in the memory mode. The problem is that if the program is large and a complex object, the cost of copying multiple times is very high, it can be used in many places. It is obvious that only one copy is the best. In this case, object lifecycle management is complicated, so c ++ introduces smart pointers. Everything has two sides. Shared_ptr is excerpted from valid tive C ++, 3rd Edition, Item 17: saves the new objects (object) to smart pointers (Intelligent pointer) in standalone statements (independent statement) for example, copy the code class Widget {public: Widget () {cout <"construct Widget !!! "<Endl ;};~ Widget () {cout <"destruct Widget !!! "<Endl ;};}; int priority () {cout <" 22222 "<endl; return 0 ;}void processWidget (int priority, std :: shared_ptr <Widget> pw) {cout <"111111" <endl;} int main () {processWidget (priority (), std :: shared_ptr <Widget> (new Widget); return 0;} the process of copying the code processWidget should be 1. new Widget 2. shared_ptr constructor 3. priority () the result I tested on llvm is also the execution order. Maybe some compilers may execute the order in the New Widget Priority () // exception shared_ptr Constructor may have memory leakage. Therefore, the best way is to write the new widget outside. Therefore, good coding habits are very important. 2. circular reference copy Code # include <iostream> using namespace std; class A; class B; typedef std: shared_ptr <A> APtr; typedef std: shared_ptr <B> BPtr; class A {public: BPtr B ;~ A () {cout <"A released" <endl ;}}; class B {public: APtr ;~ B () {cout <"B released" <endl ;}}; int main () {APtr a (new ()); BPtr B (new B (); a-> B = B; // 1 B-> a = a; // 2 cout <"over !! "<Endl; return 0;} to solve this problem, we need to introduce A weak reference smart pointer to weak_ptr to copy the Code class A; class B; typedef std :: shared_ptr <A> APtr; typedef std: shared_ptr <B> BPtr; typedef std: weak_ptr <A> AWeakPtr; typedef std: weak_ptr <B> BWeakPtr; class A {public: BWeakPtr B; // pay attention to this ~ A () {cout <"A released" <endl ;}}; class B {public: AWeakPtr a; // pay attention to this ~ B () {cout <"B released" <endl ;}}; int main () {APtr a (new ()); BPtr B (new B (); a-> B = B; B-> a = a; return 0;} copy the two pointers of the code and strong in the oc, weak is very familiar. Another usage scenario of weak_ptr: when the class object is managed by shared_ptr, you need to pass the current class object as a parameter to other functions in the function defined by the class, in this case, a shared_ptr must be passed; otherwise, the semantics of the shared_ptr management class object cannot be maintained (because a raw pointer Points to this class object, and shared_ptr does not count the reference of this class object, it is very likely that shared_ptr has released the Class Object resource, and the called function is still using the Class Object-obviously, this will certainly produce an error ). Excerpt: Let's take a look at the examples on the official website: copy the Code # include <memory> # include <iostream> struct Good: std: enable_shared_from_this <Good> {std :: shared_ptr <Good> getptr () {return shared_from_this () ;}}; struct Bad {std: shared_ptr <Bad> getptr () {return std :: shared_ptr <Bad> (this );}~ Bad () {std: cout <"Bad ::~ Bad () called \ n ";}}; class CObj: public std: enable_shared_from_this <CObj> {friend class CObjMgr; protected: CObj () {} // only CObjMgr can be created and deleted ~ CObj () {}}; int main () {// Good: the two shared_ptr's share the same object std: shared_ptr <Good> gp1 (new Good); std:: shared_ptr <Good> gp2 = gp1-> getptr (); std: cout <"gp2.use _ count () =" <gp2.use _ count () <'\ n'; // Bad, each shared_ptr thinks it's the only owner of the object std: shared_ptr <Bad> bp1 (new Bad); std :: shared_ptr <Bad> bp2 = bp1-> getptr (); std: cout <"bp2.use _ count () =" <bp2.u Se_count () <'\ n';} // UB: double-delete of Bad copy Code 1. you cannot call shared_from_this () in the constructor. Because weak_ptr, a member of enable_shared_from_this, is initialized in shared_ptr, weak_ptr is still null at this time. 2. why can't we use the this pointer internally? Because shared_ptr is used in our program to manage pointers, if we use the original pointer in the internal transfer process of the class, the reference of shared_ptr inside the class will not be noticed, it is possible that shared_ptr has been released when we pass it in. Unique_ptr is much simpler. unique_ptr "unique" has the object it refers to. Only one unique_ptr can point to a given object (by prohibiting copy semantics and only moving semantics ). Replace the normal pointer to copy the code void foo () {// Insecure code X * px = new X; // do something, exception may occurs delete px; // may not go here} unique_ptr <X> px (new X); copy the code and return the unique_ptr object in the function <X> foo () {unique_ptr <X> px (new X); // do something return px; // move semantics} into the container vector <unique_ptr <string> vs {new string {"1111"}, new string {"2222 "}, new string {"3333" }}; vector <unique_ptr <string> v; unique_ptr <string> test (new string ("11111"); v. push_back (std: move (test); // use the move syntax to directly hold the array std: shared_ptr <int> p (new int [10], [] (int * p) {delete [] p;}); // or use helperstd: shared_ptr <int> p (new int [10], std :: default_delete <int []> ());

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.