18

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?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
ISTB
  • 1,799
  • 3
  • 22
  • 31

3 Answers3

29

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.

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
john
  • 7,897
  • 29
  • 27
  • 1
    Just to give a reason why: shared_ptr does not consider the raw pointer because there is no way shared_ptr could know about it. If you think about how you would implement a shared_ptr yourself then you will see that you can't detect if there are any raw pointers to the data. – Wutz Sep 14 '12 at 13:14
  • 1
    +1. Also, this is why you should `new` the object on the same line as you create the `shared_ptr`. Even better, use [`make_shared`](http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared) – Aaron McDaid Sep 14 '12 at 13:59
  • Thanks, in fact I agree that there is no way in finding out if a raw pointer is pointing to the object. In this case it is just dangerous for the raw pointer because it will point to a destroyed object because the shared_ptr will destroy it when out of scope – ISTB Sep 14 '12 at 14:32
  • 1
    what if he passes the raw ptr to a second shared_ptr, will the first shared_ptr still counter incease? – jiggunjer Jul 02 '15 at 15:28
5

no. The shared pointer will delete it.

If you have a third party library providing you with a pointer, you need to be sure that you delete it in the correct way. If the 3rd party lib allocated it with 'malloc' for example, then you need to use the implementation of 'free' that the lib uses. You need to be sure how it was allocated.

Does the library offer a way to destroy objects it provides you with? In which case you should use that function to destroy it.

Pete
  • 4,784
  • 26
  • 33
2

No, ClassA object will be destroyed. Unless you didn't copied shared_ptr somewhere out of scope so its reference counter is > 1.

Rost
  • 8,779
  • 28
  • 50