C++ raw pointer and std::shared_ptr

偶尔善良 提交于 2019-12-21 07:02:14

问题


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?


回答1:


No it won't. By giving the pointer to shared_ptr you are giving shared_ptr the responsibilty for deleteing it. It will do this when the last shared_ptr object refering to it no longer exists. Raw pointers don't count.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/12425073/c-raw-pointer-and-stdshared-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!