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?


基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01