vector of references

T

The Directive

I'm confused as to why C++ does not allow to create a vector of
references (even though a vector of pointers can be created). I read
some old threads about it but I still don't fully understand it. Can
someone help? What about array of references, how would I declare it?
 
J

Jeff Schwab

The said:
I'm confused as to why C++ does not allow to create a vector of
references (even though a vector of pointers can be created). I read
some old threads about it but I still don't fully understand it. Can
someone help? What about array of references, how would I declare it?

References aren't actually separate objects, they're just alternative
names for existing variables. Sometimes run-time entities like unnamed
pointers exist to make references work right, but references may not
have any run-time representation at all. A container of references
wouldn't make any more sense than an array of some purely syntactic element.
 
N

Nick Hounsome

The Directive said:
I'm confused as to why C++ does not allow to create a vector of
references (even though a vector of pointers can be created). I read
some old threads about it but I still don't fully understand it. Can
someone help? What about array of references, how would I declare it?

Because
1. references must be bound to real objects at definition time hence you can
never dynamically allocate an array of references.
2. They cannot be rebound to anything else ever.

Also if you look at the vector code it allocates a bit lump raw data then
uses placement new to construct stuff into it.
You cannot construct a reference.

Arrays should work:

int& a[] = { x, y,z };

but a[2] = z will set y==z NOT change a

I don't see any reason in principle why you couldn't have a list<int&> in
certain restricted circumstances (i.e. no defaults) but the standard
probably doesn't allow it and it wouldn't be portable.

I'm not sure why you want a vector of references but you could create your
own adaptor class that took a vector<X*> (or more generally a pair of
iterators) and did all the dereferencing so that what appeared to change the
content of the adaptor would actually change the things pointed to by the
vector.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,351
Latest member
RoxiePulli

Latest Threads

Top