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

后端 未结 6 1160
执念已碎
执念已碎 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:25

    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:

    • use smart pointers (boost::shared_ptr for example)
    • use a specialized container: Boost Pointer Container Library

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

    Hope it helps :)

提交回复
热议问题