Returning an STL vector from a function - copy cost

后端 未结 2 2012
执笔经年
执笔经年 2021-01-31 20:20

When you return an stl vector from a function:

vector getLargeArray() {  ...  }

Is the return going to be an expensive copy operatio

2条回答
  •  自闭症患者
    2021-01-31 20:47

    You are very likely to get return value optimization, depending on the structure of the function body. In C++11 you could also benefit from move semantics. Returning by value certainly has cleaner semantics, and I would see it as the preferred option, unless profiling proves it to be costly. There is a good related article here.

    Here is a small example with a verbose dummy class, compiled with no optimization or C++11 support, using an old-ish version of GCC (4.3.4):

    #include 
    #include 
    struct Foo
    {
      Foo() { std::cout << "Foo()\n"; }
      Foo(const Foo&) { std::cout << "Foo copy\n"; }
      Foo& operator=(const Foo&) { 
        std::cout << "Foo assignment\n"; 
        return *this;
      }
    };
    
    std::vector makeFoos()
    {
      std::vector tmp;
      tmp.push_back(Foo());
      std::cout << "returning\n";
      return tmp;
    }
    
    int main()
    {
      std::vector foos = makeFoos();
    }
    

    The result on my platform is that all copying happens before the function return. If I compile with C++11 support, then the push_back results in a move copy rather than a C++03 copy construction.

提交回复
热议问题