Class vector
has two push_back
implementations:
void push_back( const T& value );
void push_back( T&& value );
The first one does copy of the element given.
The second tries to "move" it by calling element's move constructor (if it's defined).
Using move
forces to pick the second implementation which is supposed to reuse the value rather than just copying one.
In this particular case this is what gonna happen:
- Vector
bar
is allocated on the stack, but its elements (42) are allocated on the heap.
- When you call
foo.push_back(...)
, foo
allocates on the heap a new vector, which is gonna be bar
s copy. Let's call it baz
:) Depending on which push_back
implementation is called the following will happen then:
void push_back( const T& value );
: in this case all bar
's elements will be copyed to baz
as well.
void push_back( T&& value );
in this case baz
will receive a pointer to bar
's elements, so no copy operations are performed. But it is crucial for understanding that bar
will be deprived of its elemets (now baz
owns them), so bar
shoun't be used after move
.
It isn't that important what kind of the elements are (plain ints or pcl::PointXYZ
), since only the first vector has allocated the memory for the elements, and the pointer to that memory is the only thing that is copyed during the move
call.
42
. However, would I be correct in saying that a smart compiler is allowed to and could figure out the optimisation, butstd::move
makes it explicit that the optimisation must take place? – Moultrie