Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ raw pointer and std::shared_ptr

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?

like image 581
ISTB Avatar asked Sep 14 '12 12:09

ISTB


People also ask

What does shared_ptr get () do?

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.

Is shared_ptr a smart pointer?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

When should you use shared_ptr?

So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object. When to use shared_ptr? Use shared_ptr if you want to share ownership of a resource.

How do I find the value of a shared pointer?

Suppose you have a shared_ptr variable named ptr . You can get the reference either by using *ptr or *ptr. get() . These two should be equivalent, but the first would be preferred.


2 Answers

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.

like image 171
john Avatar answered Sep 18 '22 23:09

john


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.

like image 39
Pete Avatar answered Sep 18 '22 23:09

Pete