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.
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()
.