C++基本指针问题

发布于 2024-09-09 07:32:03 字数 823 浏览 1 评论 0原文

我有一些共享指针 shared_ptr;指针1(新T(1));

现在,在代码的其他部分中,我有一个 pointer2 的显式副本(猜测它将存储在 std::map 或其他容器中)。假设复制是像 map.insert(make_pair(key1,pointer1)); 那样完成的。

我仅使用第二个副本来预缓存一些数据,这意味着如果主指针已经无效,则无需存储第二个指针。 在这种情况下我应该做什么?

如果我知道 pointer1 在我的代码的其他部分变得无效,是否有任何方法可以强制第二个指针的内存释放?

或者我应该采取丑陋的方式 - 时不时地检查我的地图是否有将 ptr.unique() 设置为 true 的指针并销毁它们?

也许有一些替代方案/建议?


编辑 - 纯代码示例

std::map<int, shared_ptr<int> > map;

{
   shared_ptr<int> pointer1(new int(5));
   map.insert(std::make_pair(0, pointer1));
}

有什么方法/技巧可以使地图包含 <0,shared_ptr[NULL]> 而不是<0, shared_ptr[5]> 这些操作发生后?

谢谢

I have some shared pointer shared_ptr<T> pointer1(new T(1));.

Now, in some other part of code I have an explicit copy of pointer2 (guess it would be stored in a std::map or some other container). Let's say that copy was done like map.insert(make_pair(key1, pointer1));.

I am using that second copy only to precache some data and this means that if the main pointer is already invalid, there is no need to store the second pointer. What should I do in this case?

Is there any way to force the memory deallocation for the second pointer if I know that pointer1 became invalid in some other part of my code?

Or should I take the ugly way - from time to time check my map for pointers which have ptr.unique() set to true and destruct them?

Maybe some alternatives / advices?


Edit - plain code sample

std::map<int, shared_ptr<int> > map;

{
   shared_ptr<int> pointer1(new int(5));
   map.insert(std::make_pair(0, pointer1));
}

Is there any way / trick to make map contain <0, shared_ptr[NULL]> instead of <0, shared_ptr[5]> after these operations happen?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初见终念 2024-09-16 07:32:03

听起来这是weak_ptr的任务:

http:// www.boost.org/doc/libs/1_40_0/libs/smart_ptr/weak_ptr.htm

尝试将它们放入您的表中而不是shared_ptr。

It sounds like this is a task for weak_ptr:

http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/weak_ptr.htm

Try putting them in your table instead of a shared_ptr.

执笔绘流年 2024-09-16 07:32:03

我仅使用第二个副本来预缓存一些数据,这意味着如果主指针已经无效,则无需存储第二个指针。这种情况我该怎么办?

你应该看看 boost::weak_ptr
如果关联的shared_ptr已被重置,那么weak_ptr就会知道这一点。

如果我知道pointer1在我的代码的其他部分变得无效,是否有任何方法可以强制第二个指针的内存释放?

不这么认为。
但如果您使用弱指针,则不需要这样做。

I am using that second copy only to precache some data and this means that if the main pointer is already invalid, there is no need to store the second pointer. What should I do in this case?

You should look at boost::weak_ptr
If the associated shared_ptr has been reset then the weak_ptr knows about it.

Is there any way to force the memory deallocation for the second pointer if I know that pointer1 became invalid in some other part of my code?

Don't think so.
But if you use weak pointer this will not be required.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文