返回没有副本的 c++ std::vector?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3721217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a c++ std::vector without a copy?
提问by static_rtti
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?
据我了解,这将返回值复制到一个新的向量 b 中。使函数返回引用或类似的东西是否允许避免复制?
采纳答案by Steve Townsend
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.
如果您的编译器支持 NRVO,则不会进行复制,前提是返回对象的函数中满足某些条件。值得庆幸的是,这最终被添加到Visual C++ 2005 (v8.0) 中,显然,如果容器很大,这会对性能产生重大影响。
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.
如果您自己的编译器文档没有说明它是否受支持,您应该能够将 C++ 代码编译为汇编程序(在优化/发布模式下)并使用简单的示例函数检查已完成的操作。
There's also an excellent broader discussion here
还有一个很好的更广泛的讨论在这里
回答by sbi
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
引用的右值(“临时对象”)的生命周期将延长到引用生命周期的末尾。因此,如果您不需要修改该向量,则执行以下操作:
const std::vector<A>& b = MyFunc();
ifyou 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.
否则,依靠 C++1x 及其右值引用和移动语义,“现在很快”就会出现并优化该副本,而无需执行任何操作。
回答by beezler
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
HTH