Question

I'm seeing some code that uses unique_ptr in some weird ways, i'm not sure if it is even legal, although it seems to compile fine on g++ with -std=c++0x

#include <memory>
#include <boost/unordered_map.hpp>

typedef std::unique_ptr< std::string > str_ptr_t;

typedef boost::unordered_map< int , str_ptr_t > map_t;

str_ptr_t& get_ptr_value(map_t& map, int key)
{
   return map[key];
};

int main()
{
  map_t map;
  str_ptr_t& ref_to_value_of_0 = get_ptr_value(map, 0);
  map[0] = std::move(ref_to_value_of_0);
};

briefly explained, the map value type is a unique_ptr< std::string >. I initialise a reference to the value of key = 0. I then proceed to move the content of that reference to the same instance value, so basically the unique_ptr is being moved onto itself. This seems that to avoid creating many instances of the pointed object, it is attempted to reuse the existing entry instance if one already exists, and then add it again. In reality the assignment is hidden inside a store interface, and the reference is returned from a get interface, but the overall sequence can be summarized in the code i show above

Besides of being a bit weird, is this valid usage of unique_ptr?

Was it helpful?

Solution

The move assignment is defined in terms of reset and release, and so it's essentially doing this:

ref_to_value_of_0.reset(ref_to_value_of_0.release())

If you work out how this is evaluated you will find it to be a safe "no-op". It releases the owned pointer, frees a null, then sets its pointer back to original value.

I don't really understand why you are doing that though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top