Returning a c++ std::vector without a copy?

吃可爱长大的小学妹 提交于 2019-11-29 01:41:14

问题


Is it possible to return a standard container from a function without making a copy?

Example code:

std::vector<A> MyFunc();

...

std::vector<A> b = MyFunc();

As far as I understand, this copies the return value into a new vector b. Does making the function return references or something like that allow avoiding the copy?


回答1:


If your compiler supports the NRVO then no copy will be made, provided certain conditions are met in the function returning the object. Thankfully, this was finally added in Visual C++ 2005 (v8.0) This can have a major +ve impact on perf if the container is large, obviously.

If your own compiler docs do not say whether or not it's supported, you should be able to compile the C++ code to assembler (in optimized/release mode) and check what's done using a simple sample function.

There's also an excellent broader discussion here




回答2:


Rvalues ("temporaries") bound to const references will have their lifetime extended to the end of the reference's lifetime. So if you don't need to modify that vector, the following will do:

const std::vector<A>& b = MyFunc();

if you need to modify the vector, just code it the way that's easiest to read until your have proof (obtained through profiling) that this line even matters performance-wise.

Otherwise rely on C++1x with its rvalue references and move semantics coming along "real soon now" and optimizing that copy out without you having to do anything.




回答3:


If you can modify the signature of the function then you can use

std::vector<A>& MyFunc(); 

or

void MyFunc(std::vector<A>& vect);

You could also return a smart pointer, but that involves newing the object.

some_smart_pointer<std::vector<A>> MyFunc();

HTH



来源:https://stackoverflow.com/questions/3721217/returning-a-c-stdvector-without-a-copy

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