Skip to content

Instantly share code, notes, and snippets.

Created July 12, 2019 21:01
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zhangxiaomu01/86c449ad9b67a99e848fb77a3cb62445 to your computer and use it in GitHub Desktop.
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
//Use the shared pointer just like the raw pointer.
shared_ptr<Dog> p2 = p; //count == 2
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