Why does storing references (not pointers) in containers in C++ not work?
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?
Solution 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.
Solution 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.
Solution 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.