我在 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
这篇关于避免使用“返回"复制对象陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)