从参数初始化数据成员的C ++ 11方法 [英] The C++11 way of initializing data members from arguments

查看:83
本文介绍了从参数初始化数据成员的C ++ 11方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到C ++ 11支持移动语义,从参数初始化数据成员时,我们应该尝试移动值而不是复制它吗?

Seeing as C++11 supports move semantics, when initializing data members from arguments, should we attempt to move the value instead of copying it?

下面是一个示例展示了在C ++ 11之前的版本中如何处理此问题:

Here's an example showing how I would approach this in pre-C++11:

struct foo {
    std::vector<int> data;

    explicit foo(const std::vector<int>& data)
        : data(data)
    {
    }
};

在这里,将调用复制构造函数。

Here, the copy constructor would be called.

在C ++ 11中,我们应该养成这样的写法吗?

In C++11, should we get into the habit of writing like this:

struct foo {
    std::vector<int> data;

    explicit foo(std::vector<int> data)
        : data(std::move(data))
    {
    }
};

此处,如果传递了参数,则将调用move构造函数以及复制构造函数是一个左值,但是好处是,如果传递了一个右值,则将调用move构造函数,而不是复制一个副本。

Here, the move constructor would be called... as well as the copy constructor if the argument passed is an lvalue, but the benefit is that if an rvalue was passed, the move constructor would be called instead of the copy one.

我想知道是否有些东西

推荐答案

我对您问题的最初答案是:

不复制您要移动的数据。如果性能存在问题,则可以使用右值引用添加构造函数:

Don't copy data that you want to move. You can add a constructor using a rvalue reference, if performance is a problem:

explicit foo(std::vector<int>&& data)
    : data(std::move(data))            // thanks to Kerrek SB
{
}

与您的问题不完全匹配,但阅读
在C ++ 11中,三分法成为五法则吗?
似乎很有用。

Not exactly matching your question, but reading Rule-of-Three becomes Rule-of-Five with C++11? seems to be useful.

编辑:

但是,对
可接受的答案在C ++ 0x中传递/移动构造函数的参数
似乎主张您的方法,尤其是使用多个参数时。
否则会有各种变体的组合爆炸。

However, the accepted answer to Passing/Moving parameters of a constructor in C++0x seems to advocate your approach, especially with more than one parameter. Otherwise there would be a combinatorial explosion of variants.

这篇关于从参数初始化数据成员的C ++ 11方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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