C ++:避免复制与“返回”语句 [英] C++ : Avoiding copy with the "return" statement
问题描述
我在C ++中有一个非常基本的问题。
如何在返回对象时避免复制?
下面是一个示例:
std :: vector< unsign int> test(const unsigned int n)
{
std :: vector< unsigned int> X;
for(unsigned int i = 0; i x.push_back(i);
}
return x;
}
根据我了解C ++的工作原理,此函数将创建2个向量:local one(x),以及将返回的x的副本。有没有办法避免复制? (我不想返回指向对象的指针,而是对象本身)
非常感谢。
编辑:根据第一个答案的额外问题:使用move semantics的那个函数的语法是什么?
此程序可以利用命名返回值优化(NRVO)。请参阅: http://en.wikipedia.org/wiki/Copy_elision
在C ++ 11中有move constructors和assignment也很便宜。您可以在这里阅读教程: http://thbecker.net/articles/rvalue_references/section_01.html p>
I have a very basic question in C++. How to avoid copy when returning an object ?
Here is an example :
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;
}
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)
Thank you very much.
EDIT : extra question according to the first answers : what would be the syntax of that function using "move semantics" ?
This program can take advantage of named return value optimization (NRVO). See here: http://en.wikipedia.org/wiki/Copy_elision
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
这篇关于C ++:避免复制与“返回”语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!