Using push_back with rvalue references?
I have the following code:
csvData.push_back(CsvDataSet(csvBlock));
Should I instead do this:
csvData.push_back(std::move(CsvDataSet(csvBlock)));
That way I save one copy operation.
Assuming CsvDataSet
to be a class: No, you shouldn't. CsvDataSet(csvBlock)
is already an rvalue. More precisely, it is an prvalue.
Therefore in both cases, void std::vector::push_back( T&& value );
will be called.
I think in your case you should use emplace_back()
.
"Appends a new element to the end of the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments that are supplied to the function."
Not sure, but I think it is equivalent for using push_back(std::move(T()))
, but maybe the downvoter correct me, please. Clarification the result should be the same, but emplace
forwards arguments to constructor and constructs elements in place, while push_back
calls move
constructor, or normal one and then moves object.
Edit: if the downvoter agrees with the reasoning presented by @user3111311 below I urge to read Example section in emplace_back()
.
emplace_back
is not redundant in C++11. There are specific forms of emplace_back
that was provided by different compilers that are non comformant and redundant (see this). However the correct form of emplace_back
taking the constructor parameters directly e.g. csvData.emplace_back(csvBlock)
is not redundant. It will construct the object in place instead of performing a move construct as void push_back(T&&)
Commented
Jan 17, 2014 at 15:33
emplace
can do that. Passing a T const&
or T&&
to emplace_back
has identical effect to passing a T const&
or T&&
to push_back
.
CsvDataSet
is a class or a function returning some value.