避免使用“返回”命令复制对象。声明 [英] Avoiding copy of objects with the "return" statement

查看:44
本文介绍了避免使用“返回”命令复制对象。声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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)?

推荐答案

该程序可以利用named返回值优化(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中,move构造函数和赋值也很便宜。您可以在此处阅读教程: 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

这篇关于避免使用“返回”命令复制对象。声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆