返回没有副本的c ++ std::vector? [英] Returning a c++ std::vector without a copy?

查看:28
本文介绍了返回没有副本的c ++ std::vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不复制的情况下从函数返回标准容器?

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

示例代码:

std::vector<A> MyFunc();

...

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

据我了解,这会将返回值复制到一个新向量 b 中.使函数返回引用或类似的东西可以避免复制吗?

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?

推荐答案

如果您的编译器支持 NRVO,那么只要返回对象的函数满足某些条件,就不会进行复制.值得庆幸的是,这最终被添加到 Visual C++ 2005 (v8.0) 显然,如果容器很大,这会对性能产生重大的 +ve 影响.

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.

如果您自己的编译器文档没有说明它是否受支持,您应该能够将 C++ 代码编译为汇编器(在优化/发布模式下)并使用简单的示例函数检查所做的工作.

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

这篇关于返回没有副本的c ++ std::vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆