c++ - Using operator[] to access a private std::map of unique_ptr -


i have class 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 sole owner of my_type objects.

i expose operator[] public member function access (perfect forwarding) my_map. like:

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

i have tried various possible definitions of operator[] :

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

but doesn't work, in end invoking deleted copy constructor of unique_ptr.

just move forward, if move my_map public interface have made tests pass, cheating of course, since trying refine modern c++ skills , think there principle have not grokked yet unique_ptr , move.

so question is: how use std::unique_ptr's in private std::map?

you should return reference.

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

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -