Avoiding copy of objects with the quot;returnquot; statement(避免使用“return复制对象.陈述)
问题描述
我有一个非常基本的 C++ 问题.返回对象时如何避免复制?
I have a very basic question in C++. How to avoid copy when returning an object ?
这是一个例子:
std::vector<unsigned int> test(const unsigned int n)
{
std::vector<unsigned int> x;
for (unsigned int i = 0; i < n; ++i) {
x.push_back(i);
}
return x;
}
据我了解 C++ 的工作原理,此函数将创建 2 个向量:本地向量 (x) 和将返回的 x 副本.有没有办法避免复制?(而且我不想返回指向对象的指针,而是返回对象本身)
As I understand how C++ works, this function will create 2 vectors : the local one (x), and the copy of x which will be returned. Is there a way to avoid the copy ? (and I don't want to return a pointer to an object, but the object itself)
使用移动语义"(在评论中说明)该函数的语法是什么?
What would be the syntax of that function using "move semantics" (which was stated in the comments)?
推荐答案
这个程序可以利用命名返回值优化 (NRVO).请参阅此处:http://en.wikipedia.org/wiki/Copy_elision
This program can take advantage of named return value optimization (NRVO). See here: http://en.wikipedia.org/wiki/Copy_elision
在 C++11 中,移动构造函数和赋值也很便宜.您可以在此处阅读教程:http://thbecker.net/articles/rvalue_references/section_01.html
In C++11 there are move constructors and assignment which are also cheap. You can read a tutorial here: http://thbecker.net/articles/rvalue_references/section_01.html
这篇关于避免使用“return"复制对象.陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:避免使用“return"复制对象.陈述


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01