我有一些共享指针 shared_ptr<T> pointer1(new T(1));
.
现在,在代码的其他部分,我有一个 pointer2
的显式拷贝(猜测它会存储在 std::map
或其他容器中)。假设复制是像 map.insert(make_pair(key1, pointer1));
这样完成的.
我只使用第二个拷贝来预缓存一些数据,这意味着如果主指针已经无效,则无需存储第二个指针。 遇到这种情况我该怎么办?
如果我知道pointer1
,有什么办法可以强制释放第二个指针的内存?在我的代码的其他部分变得无效?
或者我应该采取丑陋的方式 - 不时检查我的 map 以寻找具有 ptr.unique()
的指针设置为 true
并摧毁它们?
也许有一些替代方案/建议?
编辑 - 纯代码示例
std::map<int, shared_ptr<int> > map;
{
shared_ptr<int> pointer1(new int(5));
map.insert(std::make_pair(0, pointer1));
}
有没有办法/技巧让 map 包含<0, shared_ptr[NULL]>
而不是 <0, shared_ptr[5]>
在这些操作发生之后?
谢谢
最佳答案
听起来这是 weak_ptr 的任务:
http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/weak_ptr.htm
尝试将它们放在您的表中而不是 shared_ptr。
关于C++基础指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3232545/