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?


- 如何提取 __VA_ARGS__? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01