Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created July 12, 2019 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/86c449ad9b67a99e848fb77a3cb62445 to your computer and use it in GitHub Desktop.
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
(*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