Boost :: shared_ptr standard container

Suppose I have a class foo and you want to use std :: map to store some boost :: shared_ptrs, for example:

class foo; typedef boost::shared_ptr<foo> foo_sp; typeded std::map<int, foo_sp> foo_sp_map; foo_sp_map m; 

If I add a new foo_sp to the card, but the key used already exists, will the existing record be deleted? For example:

 foo_sp_map m; void func1() { foo_sp p(new foo); m[0] = p; } void func2() { foo_sp p2(new foo); m[0] = p2; } 

Will the original pointer (p) be freed if it is replaced by p2? I am sure this will happen, but I thought it was worth asking / sharing.

+6
c ++ std smart-pointers stdmap
source share
3 answers

First, your question title says boost :: auto_ptr, but actually you mean boost :: shared_ptr

And yes, the original pointer will be freed (if there are no further general references to it).

+7
source share

It depends on what happens in your section ...

The container class contains copies of foo_sp instances when you execute m[0] = p2; the copy of p that was originally in this place is beyond the scope. At this time, it will be deleted if there are no other foo_sp referencing it.

If the copy that was declared on the second line is foo_sp p(new foo); still exists, memory will not be freed. The record will be deleted after deleting all links to it.

+1
source share

Since stackoverflow doesn't allow me to comment, I will just answer.: /

I do not see the "p" going out of scope, so the object it points to will not be freed. "p" will still point to it.

0
source share

All Articles