Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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