简体   繁体   English

返回没有副本的c ++ std :: vector?

[英]Returning a c++ std::vector without a copy?

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. 据我所知,这会将返回值复制到一个新的向量b中。 Does making the function return references or something like that allow avoiding the copy? 使函数返回引用或类似的东西可以避免复制吗?

If your compiler supports the NRVO then no copy will be made, provided certain conditions are met in the function returning the object. 如果您的编译器支持NRVO,那么只要在返回对象的函数中满足某些条件,就不会进行复制。 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. 值得庆幸的是,这最终是在Visual C ++ 2005(v8.0)中添加的。如果容器很大,这显然会对perf产生重大影响。

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 还有一个很好的更广泛的讨论在这里

Rvalues ("temporaries") bound to const references will have their lifetime extended to the end of the reference's lifetime. 绑定到const引用的Rvalues(“temporaries”)将其生命周期延长到引用生命周期的末尾。 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. 否则依赖C ++ 1x及其右值引用并移动语义“即将推出”并优化该副本而无需执行任何操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM