Re: vector.push_back - pushes values or references?
Siam wrote:
void push_back( const TYPE& val );
Maybe, but that's not required by the language definition. These things
are specified in a different way. The requirement is that
vec.push_back(object) puts a copy of object into vec. Passing by value
is okay, as is passing by const reference.
I wouldve thought that means the int i pass to the vector isn't
copied, but a reference to the original int is placed in the vector.
However, the above code returns 3, not 4, indicating the int has been
copied into the vector (on printing memory addresses, the ints are
stored in different memory addresses). My question is, why does the
push_back function take a reference, but yet still store a copy of the
object in the vector?
The reason for storing by value is that that's what the specification
says. <g> The design of STL assumes that objects are cheap to create and
to copy, so STL algorithms and containers deal with values, not
references. If you need reference semantics, use TR1's reference_wrapper
(also available from Boost), or use vector<TYPE*>. In both cases you
have to ensure that your objects hang around at least as long as the
container does. (For more details on reference_wrapper, see chapter 8 of
my book, "The Standard C++ Library Extension"; for details on TR1's
shared_ptr, see chapter 2).
--
-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)