C ++原始指针和std :: shared_ptr [英] C++ raw pointer and std::shared_ptr

查看:152
本文介绍了C ++原始指针和std :: shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 std :: shared_ptr ,在我的软件开发期间,我遇到了一对夫妇
的情况,让我怀疑内存管理。我有一个第三方库,
给我总是从函数的原始指针,在我的代码中我将它们
转换为 std :: shared_ptr (从std而不是boost。顺便说一下,
的区别是什么?)。所以让我们说,我有以下代码:

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);

当共享指针超出范围时,现在会发生什么?
现在我退出函数)。 ClassA 对象是否仍然存在,因为原始指针
指向它?

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?

推荐答案

不会。通过给指针shared_ptr你给予shar​​ed_ptr的责任删除它。当引用它的最后一个shared_ptr对象不再存在时,它会这样做。原始指针不计数。

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.

这篇关于C ++原始指针和std :: shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆