Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert std::unique_ptr into boost:ptr_map

I'm moving some old code to c++14, it used the deprecated auto_ptr and that worked well with boost:ptr_map, you could do:

auto_ptr<Foo> foo(new Foo);
boost:map_ptr<int, Foo> m;
m.insert(5, foo);

Now, replacing that auto_ptr with unique_ptr, it doesn't compile:

unique_ptr<Foo> foo(new Foo);
boost:map_ptr<int, Foo> m;
m.insert(5, foo);            // Does not compile
m.insert(5, move(foo));      // Does not compile either,
                             // this should be the right thing to do
m.insert(5, move.release()); // Does compile, but isn't exception safe

Is map_ptr API just not up to date yet?

Edit based on responses, using map of unique_ptr is not a good option in my case because it requires rewrite of a fair amount of code. I really wanted to make it work with map_ptr, I'm dealing with some old code and I wish to make minimum changes.

like image 521
rahenri Avatar asked Dec 09 '25 10:12

rahenri


1 Answers

I think in C++14 what you want is this:

std::unordered_map<int, std::unique_ptr<Foo>> x;
x.emplace(5, std::make_unique<Foo>());

You don't need those old boost _ptr containers any more, they were basically workarounds for the lack of an owning, zero overhead pointer that could safely be handled in containers (i.e. unique_ptr).

like image 153
Nir Friedman Avatar answered Dec 11 '25 01:12

Nir Friedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!