問題描述
我在 C++ 中有一個非常基本的問題.返回對象時如何避免復(fù)制?
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;
}
據(jù)我了解 C++ 的工作原理,此函數(shù)將創(chuàng)建 2 個向量:本地向量 (x) 和將返回的 x 副本.有沒有辦法避免復(fù)制?(而且我不想返回指向?qū)ο蟮闹羔?,而是返回對象本?
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)
使用移動語義"(在評論中說明)的函數(shù)的語法是什么?
What would be the syntax of that function using "move semantics" (which was stated in the comments)?
推薦答案
該程序可以利用命名返回值優(yōu)化 (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 中有移動構(gòu)造函數(shù)和賦值,它們也很便宜.您可以在此處閱讀教程: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
這篇關(guān)于避免使用“返回"復(fù)制對象陳述的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!