Returning a c++ std::vector without a copy?(返回没有副本的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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回没有副本的c ++ std::vector?
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
