In this code:
// build string requiring a bunch of processing
std::wstring xmlstr=xml->GetXml();
{
std::lock_guard<std::mutex> guard(my_mutex);
m_deque.push_back(std::move(xmlstr)); // << note the std::move
}
Is it more efficient to use std::move
in this case to reduce making copies?
In this code:
// build string requiring a bunch of processing
std::wstring xmlstr=xml->GetXml();
{
std::lock_guard<std::mutex> guard(my_mutex);
m_deque.push_back(std::move(xmlstr)); // << note the std::move
}
Is it more efficient to use std::move
in this case to reduce making copies?
3 Answers
Reset to default 5Is it more efficient to use
std::move
in this case to reduce making copies?
Yes, it is. push_back
has an overload taking rvalue reference which will avoid copying. This is true for any container having push_back
, including std::deque
.
Yes, the move semantic is relatively faster than copying. You can always benchmark it if you are not sure. For example https://quick-bench.com/q/aJTHVE5uIXgY2cvG4LJYr28tXKY
No. for std::string
.
#include <iostream>
#include <string>
#include <vector>
#include <memory>
int main() {
std::string willmove{"12457"};
std::string willcopy{"1245785"};
std::cout << "addr for move=" << static_cast<void *>(willmove.data()) << "\n";
std::cout << "addr for copy=" << static_cast<void *>(willcopy.data()) << "\n";
std::vector<std::string> v;
v.push_back(std::move(willmove));
v.push_back(willcopy);
std::cout << "addr after move=" << static_cast<void *>(v[0].data()) << "\n"; //address of data was change mean there is new allocate memory.
std::cout << "addr after copy=" << static_cast<void *>(v[1].data()) << "\n\n";
auto a = std::make_unique<std::string>("12354");
std::cout << "addr for ptr=" << static_cast<void *>(a->data()) << "\n";
std::vector<std::unique_ptr<std::string>> v2;
v2.push_back(std::move(a));
std::cout << "addr after move ptr=" << static_cast<void *>(v2[0]->data()) << "\n"; //address doesn't changed no new allocate memory.
}
result will be like
addr for move=0x7ffe1ab4afc0
addr for copy=0x7ffe1ab4af88
addr after move=0x57cc0c86d300
addr after copy=0x57cc0c86d320
addr for ptr=0x57cc0c86d2d0
addr after move ptr=0x57cc0c86d2d0
- godbolt
- no new heap allocate memory (std::string store data in heap) when copy = faster.
- It will do the same with all standard API container.