Search code examples
c++referenceinitializationtemporary-objects

assignment and reference initialization from a temporary


suppose i have the following:

boost::unordered_map< string , someValueType > map;
someValueType& value = map[ "key" ] = someValueType();

the last line contains:

  • a temporary constructed instance of someValueType
  • an assignment of the temporary into a new map entry
  • initialization of a reference to the map entry

so if next line is:

   value.someProperty = 42;

this will try to change the map entry right? not the original temporary?

I know in this case if the reference couldn't take a temporary because it is non const (so a compiler error or the absence of one would answer my question), but if i added the const to the reference declaration, i'm not sure what the evaluation rules would say in this case


Solution

  • That's true. You have an initialization with an assignment expression on the right:

    someValueType & value = (map["key"] = someValueType());
    

    In fact, this is equivalent to:

    someValueType & value = map["key"];
    

    This is because the []-operator creates a new element if one doesn't already exist for that key.

    Binding the map entry to a const reference makes no difference. However, if you know that the key is guaranteed to exist, then you can bind a const reference to the mapped value even if you only have a constant reference to the map itself:

    void (MapType const & m)
    {
        someValueType const & = m.find("key")->second;
    }
    

    This would be an error of course if the key didn't exist, since you'd be dereferencing the end iterator.