Why does storing references (not pointers) in containers in C++ not work?

前端 未结 3 526
梦如初夏
梦如初夏 2020-11-29 06:43

In my program I have a STL set.

set myStrings;

To improve the efficiency of my code I changed it to hold, only pointers. (I d

相关标签:
3条回答
  • 2020-11-29 06:49

    As Containers store objects and references are not objects. In case you are at c++ 11, you can use std::reference_wrapper to wrap things to assignable objects.

    http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

    std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.

    0 讨论(0)
  • 2020-11-29 06:52

    Not directly relevant to the "why", but to give an answer to the implied desire to do this, I would mention that the c++11 standard library has std::reference_wrapper to enable this. It is implicitly convertible to a reference and it is storable in standard containers.

    0 讨论(0)
  • 2020-11-29 06:58

    Containers store objects. References are not objects.

    The C++11 specification clearly states (§23.2.1[container.requirements.general]/1):

    Containers are objects that store other objects.

    0 讨论(0)
提交回复
热议问题