C++基础指针问题

标签 c++ shared-ptr lifetime destruction

我有一些共享指针 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/

相关文章:

java - 如何设置JAssimp?

c++ - QRegExp html行

c++ - For循环间隔

c++ - Qt Creator 不构建(Qt 5.3,最新的 Qt creator 代码)

c++ - 任何人都知道有什么计划让 ^ 成为 shared_ptr<T> 的简写吗?

c++ - 将 shared_ptr 与指向指针的指针一起使用时出现编译器错误

c++ - 如何从此指针获取 std::weak_ptr<MyClass> ?

使用rust 错误 : borrow occurs after drop a mutable borrow

rust - 如何为具有生命周期成员的结构派生 serde::Deserialize

multithreading - 如何将对堆栈变量的引用传递给线程?