1
votes

I have a class with a private std::map of unique_ptr:

class MyClass{
std::map <KeyType, std::unique_ptr<my_type>> my_map;
...
};

I chose unique_ptr because my_map is the sole owner of my_type objects.

I would like to expose an operator[] public member function to access (perfect forwarding) my_map. Something like:

// my_class is of type MyClass
auto ptr = my_type_factory(...); // my_type_factory returns a std::unique_ptr<my_type>
....
my_class[1] = std::move(auto_ptr);

I have tried with various possible definitions of operator[] :

class MyClass{
....
public:
auto operator[](KeyType && key) { return my_map[std::forward<KeyType>(key)]; } 
// or return & my_map[...];
};

but it doesn't work, in the end I am always invoking the deleted copy constructor of unique_ptr.

Just to move forward, if I move my_map to the public interface I have made all my tests pass, but this is cheating of course, since I am trying to refine my modern C++ skills and I think there is some principle which I have not grokked yet with unique_ptr and move.

So my question is: how do I use std::unique_ptr's in a private std::map?

1
@LogicStuff: Can't be dupe of that one, just by the title.einpoklum

1 Answers

4
votes

You should return a reference.

auto & operator[](KeyType && key) { return my_map[std::forward<KeyType>(key)]; }