C++基本指针问题
我有一些共享指针 shared_ptr
。
现在,在代码的其他部分中,我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来这是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.
你应该看看 boost::weak_ptr
如果关联的shared_ptr已被重置,那么weak_ptr就会知道这一点。
不这么认为。
但如果您使用弱指针,则不需要这样做。
You should look at boost::weak_ptr
If the associated shared_ptr has been reset then the weak_ptr knows about it.
Don't think so.
But if you use weak pointer this will not be required.