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

后端 未结 6 1159
执念已碎
执念已碎 2020-12-02 19:55

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 re

6条回答
  •  悲哀的现实
    2020-12-02 20:24

    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;
    

提交回复
热议问题