How to avoid the copy when I return

喜夏-厌秋 提交于 2019-12-01 15:15:32

问题


I have a function which returns a vector or set:

set<int> foo() {
    set<int> bar;
    // create and massage bar
    return bar;
}

set<int> afoo = foo();

In this case, I create a temporary memory space in function foo(), and then assign it to afoo by copying. I really want to avoid this copy, any easy way I can do this in C++11? I think this has to do with the rvalue thing.

OK, update to the question: If I am going to return an object defined by myself, not the vector or set thing, does that mean I should define a move constructor? like this:

class value_to_return {
  value_to_return (value_to_return && other) {
    // how to write it here? I think std::move is supposed to be used?
  }
}

THanks!!!


回答1:


Modem C++ compiler will implement: given a type T:

  • If T has an accessible copy or move constructor, the compiler may choose to elide the copy. This is the so-called (named) return value optimization (RVO), which was specified even before C++11 and is supported by most compilers.
  • Otherwise, if T has a move constructor, T is moved(Since C++11).
  • Otherwise, if T has a copy constructor, T is copied.
  • Otherwise, a compile-time error is emitted.



回答2:


Check out return value optimization. A modern compiler will optimize this situation, and in straightforward situations like these, no copy will be made on any of the major compilers.

In principle, you could also create your object outside the function, and then call the function and pass the object to it by reference. That would be the old way of avoiding a copy, but it is unnecessary and undesirable now.




回答3:


I usually work around this by having function signature as

void foo(set<int> *x)

Just pass it by reference or the other option is already mentioned in the comment.

Edit: I have changed the argument type to illustrate that x could be changed.

      set<int> s;
      foo(&s);

This is only preferred when you have an old compiler. I suppose that could be the case with some of the projects.

And, better thing to do will be Either to use move semantics with c++11. Or go ahead returning the container and look into RVO in modern compilers.



来源:https://stackoverflow.com/questions/18157090/how-to-avoid-the-copy-when-i-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!