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

江枫思渺然 提交于 2019-11-26 12:44:40

问题


In my program I have a STL set.

set<string> myStrings;

To improve the efficiency of my code I changed it to hold, only pointers. (I don\'t need actual string copies to be stored.)

set<string*> myStrings;

I have read that it is a good practice to substitute pointers with references when possible. (Of course, only if the actual functionality of a pointer is not needed.)

set<string&> myStrings;

The latter one gives me a lot of compiler errors, though. Why is it not possible to use references as container elements?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4010937/why-does-storing-references-not-pointers-in-containers-in-c-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!