开发者

C++ basic pointer question

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开发者_Go百科 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜