On 9/19/2017 5:56 PM,
porp...@gmail.com wrote:
>
> Could you please explain me why references cannot be stored in STL containers.
They can't be stored DIRECTLY in containers.
Most containers, and in particular those in the standard library, don't
support reference element type because it would need extra machinery and
interface semantics to handle the not-object-ness of references, e.g.
that you can't have a pointer to a reference, which might be needed
internally in the container's code.
> I found that one of the reasons is that reference cannot be re-initialized.
> If this is true then why the "T * const" may be stored in STL containers ?
A pointer is copyable value, and when stored it's an object.
• • •
Let's say that you want a vector of references to objects of the same type.
Since you can't do that, simply store raw pointers:
#include <iostream>
#include <vector>
using namespace std;
auto main()
-> int
{
int a = 100, b = 200, c = 300;
vector<int*> values;
for( auto const p : {&a, &b, &c} ) { values.push_back( p ); }
++a; ++b; ++c;
for( int const* const p : values ) { cout << *p << " "; }
cout << endl;
}
Output:
101 201 301
Cheers & hth.,
- Alf