Created
July 12, 2019 21:01
-
-
Save zhangxiaomu01/86c449ad9b67a99e848fb77a3cb62445 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void fooFunc(){ | |
//We will have a count to keep track of how many pointers are pointing to the object. | |
shared_ptr<Dog> p(new Dog("Gunner")); // count == 1 now | |
//This is not allowed | |
//shared_ptr<Dog> pt = new Dog("Smile"); | |
//Returns the raw pointer. | |
//In general, avoid using raw pointer when use smart pointers | |
Dog* ptr = p.get(); | |
//We can dereference the smart pointer just like the raw pointer | |
(*p).bark(); | |
//Use the shared pointer just like the raw pointer. | |
p->bark(); | |
{ | |
shared_ptr<Dog> p2 = p; //count == 2 | |
p2->bark(); | |
cout << p.use_count() << endl; //Output how many pointers we have | |
} | |
p->bark(); //count == 1 | |
}// count will be 0 when code executes to here, and Gunner will be deleted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment