difference between const <type>& and const <type>

I came across the following declaration of vector,

typedef std::vector<const xyz&> xyzTypeVector_t;


where xyz is a union of structs


Can someone tell me the difference between

typedef std::vector<const xyz> xyzTypeVector_t;

and

typedef std::vector<const xyz&> xyzTypeVector_t;
Study about references. The & makes a reference to another variable, while the lack of it just copies it. The difference is huge: A copied item can be modified while the original is kept the same (although this point is moot if const is used like in your example). Another important difference is the fact that some classes do not allow copy construction (they don't expose a copy constructor), such as std::istream and std::ostream.

The topic is not difficult but it is not trivial. Best if you look up the topic in a good book or a good tutorial online. Try this site's tutorial.
closed account (zb0S216C)
The two cannot be fairly compared since a "std::vector" of references is not allowed. Internally, there's a pointer to a region of memory. If the specified type is of type reference, the internal declaration of the pointer would be a pointer to a reference to a "T", which isn't allowed. In addition, the type a "std::vector" holds must be copy-assignable. Declaration aside, this declaration:

DeepBlack wrote:
"typedef std::vector<const xyz&> xyzTypeVector_t;"

...is purely implementation-defined because an implementation may or may not reserve storage for a reference. Let's a assume no storage is set aside for a reference. Pushing and popping references wouldn't make any sense; how would you push/pop something that doesn't technically exists in memory? You can't.

Now let's assume there was space reserved for a reference. Pushing and popping would be OK, but the declaration is not OK, because an array of references is not allowed, and the internal pointer is still a pointer to a reference to a "T".

Now let's assume the declaration is valid. If a temporary actual "xyz" parameter was pushed, the actual parameter would be bound to the reference within the "std::vector". If the type was not of type reference to a "T", the actual parameter would be copied only if the "union" has a copy-constructor.

Wazzak
Last edited on
Thank you for the responses!

...is purely implementation-defined because an implementation may or may not reserve storage for a reference. Let's a assume no storage is set aside for a reference. Pushing and popping references wouldn't make any sense; how would you push/pop something that doesn't technically exists in memory? You can't.


I don't know either if this would work, because I only see this declaration in the code but it is not used anywhere. I was curious to know of what use this could be anyway.
Topic archived. No new replies allowed.