C++ raw pointer and std::shared_ptr

ISTB picture ISTB · Sep 14, 2012 · Viewed 12.1k times · Source

I am working with std::shared_ptr and during my software development I met a couple of cases that let me doubt about memory management. I had a third party library that gave me always raw pointers from functions and in my code I was transforming them into std::shared_ptr (from std and not from boost. By the way what is the difference between the two?). So let's say I have the following code:

ClassA* raw = new ClassA;
std::shared_ptr<ClassA> shared(raw);

What happens now when the shared pointer goes out of scope (let's say it was declared locally in a function and now I am exiting the function). Will the ClassA object still exist because a raw pointer is pointing to it?

Answer

john picture john · Sep 14, 2012

No it won't. By giving the raw pointer to the shared_ptr, you are giving shared_ptr the responsibility of deleting it. It will do this when the last shared_ptr object referencing your ClassA instance no longer exists. Raw pointers don't count.