Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::shared_ptr standard container

Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.:

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 map but the key used already exists, will the existing entry 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 when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing.

like image 698
Rob Avatar asked Sep 26 '08 14:09

Rob


People also ask

What is Boost shared_ptr?

shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.

What is a shared_ptr in C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

Should I use shared_ptr or unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Can I convert shared_ptr to unique_ptr?

In short, you can easily and efficiently convert a std::unique_ptr to std::shared_ptr but you cannot convert std::shared_ptr to std::unique_ptr .


2 Answers

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

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

like image 110
Seb Rose Avatar answered Sep 27 '22 19:09

Seb Rose


It depends on what happens in your ... section

Your container class contains copies of instances of foo_sp, when you execute m[0] = p2; the copy of p that was originally in that place goes out of scope. At that time it will be deleted if there are no other foo_sp refers to it.

If the copy that was declared in the second line foo_sp p(new foo); is still around then the memory will not be deallocated. The entry will be delete once all references to it have been removed.

like image 31
Harald Scheirich Avatar answered Sep 27 '22 19:09

Harald Scheirich