Why Can't I store references in a `std::map` in C++?

C++DictionaryReferenceStdStdmap

C++ Problem Overview


I understand that references are not pointers, but an alias to an object. However, I still don't understand what exactly this means to me as a programmer, i.e. what are references under the hood?

I think the best way to understand this would be to understand why it is I can't store a reference in a map.

I know I need to stop thinking of references as syntactic suger over pointers, just not sure how to :/

C++ Solutions


Solution 1 - C++

They way I understand it, references are implemented as pointers under the hood. The reason why you can't store them in a map is purely semantic; you have to initialize a reference when it's created and you can't change it afterward anymore. This doesn't mesh with the way a map works.

Solution 2 - C++

You should think of a reference as a 'const pointer to a non-const object':

MyObject& ~~ MyObject * const

Furthermore, a reference can only be built as an alias of something which exists (which is not necessary for a pointer, though advisable apart from NULL). This does not guarantee that the object will stay around (and indeed you might have a core when accessing an object through a reference if it is no more), consider this code:

// Falsifying a reference
MyObject& firstProblem = *((MyObject*)0);
firstProblem.do(); // undefined behavior

// Referencing something that exists no more
MyObject* anObject = new MyObject;
MyObject& secondProblem = *anObject;
delete anObject;
secondProblem.do(); // undefined behavior

Now, there are two requirements for a STL container:

  • T must be default constructible (a reference is not)
  • T must be assignable (you cannot reset a reference, though you can assign to its referee)

So, in STL containers, you have to use proxys or pointers.

Now, using pointers might prove problematic for memory handling, so you may have to:

DO NOT use auto_ptr, there is a problem with assignment since it modifies the right hand operand.

Hope it helps :)

Solution 3 - C++

The important difference apart from the syntactic sugar is that references cannot be changed to refer to another object than the one they were initialized with. This is why they cannot be stored in maps or other containers, because containers need to be able to modify the element type they contain.

As an illustration of this:

A anObject, anotherObject;
A *pointerToA=&anObject;
A &referenceToA=anObject;

// We can change pointerToA so that it points to a different object
pointerToA=&anotherObject;

// But it is not possible to change what referenceToA points to.
// The following code might look as if it does this... but in fact,
// it assigns anotherObject to whatever referenceToA is referring to.
referenceToA=anotherObject;
// Has the same effect as
// anObject=anotherObject;

Solution 4 - C++

actually you can use references in a map. i don't recommend this for big projects as it might cause weird compilation errors but:

    map<int, int&> no_prob;
    int refered = 666;
    no_prob.insert(std::pair<int, int&>(0, refered)); // works
    no_prob[5] = 777; //wont compile!!! 
    //builds default for 5 then assings which is a problem
    std::cout << no_prob[0] << std::endl; //still a problem
    std::cout << no_prob.at(0) << std::endl; //works!!

so you can use map but it will be difficult to guaranty it will be used correctly, but i used this for small codes (usually competitive) codes

Solution 5 - C++

A container that stores a reference has to initialize all its elements when constructed and therefore is less useful.

struct container
{
   string& s_;           // string reference
};

int main()
{
   string s { "hello" };
   //container {};       // error - object has an uninitialized reference member
   container c { s };    // Ok
   c.s_ = "bye";
   cout << s;            // prints bye
}

Also, once initialized, the storage for the container elements cannot be changed. s_ will always refer to the storage of s above.

Solution 6 - C++

This post explains how pointers are implemented under the hood - http://www.codeproject.com/KB/cpp/References_in_c__.aspx, which also supports sebastians answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionng5000View Question on Stackoverflow
Solution 1 - C++Sebastiaan MView Answer on Stackoverflow
Solution 2 - C++Matthieu M.View Answer on Stackoverflow
Solution 3 - C++Martin BView Answer on Stackoverflow
Solution 4 - C++EytanView Answer on Stackoverflow
Solution 5 - C++tcbView Answer on Stackoverflow
Solution 6 - C++Chethan RavindranathView Answer on Stackoverflow