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

查看:307
本文介绍了返回一个没有副本的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)如果容器很大,这可能对perf造成很大的影响。

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.

更广泛的讨论这里

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

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