最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Will adding std::string items to std::deque with std::move be more efficient? - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question edited Feb 7 at 0:19 Remy Lebeau 596k36 gold badges498 silver badges843 bronze badges asked Feb 6 at 23:51 user3161924user3161924 2,3071 gold badge23 silver badges42 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 5

Is 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.
发布评论

评论列表(0)

  1. 暂无评论