 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
The Directive Guest
|
Posted: Sat Dec 27, 2003 7:53 pm Post subject: vector of references |
|
|
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?
|
|
| Back to top |
|
 |
Jeff Schwab Guest
|
Posted: Sat Dec 27, 2003 7:55 pm Post subject: Re: vector of references |
|
|
The Directive wrote:
| Quote: | 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.
|
|
| Back to top |
|
 |
Nick Hounsome Guest
|
Posted: Sun Dec 28, 2003 10:04 am Post subject: Re: vector of references |
|
|
"The Directive" <the_directive (AT) hotmail (DOT) com> wrote
| Quote: | 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.
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|