是否有必要从不同的类定义移动构造函数? [英] Is it necessary to define move constructors from different classes?

查看:96
本文介绍了是否有必要从不同的类定义移动构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

struct X
{
    Y y_;

    X(const Y & y) :y_(y) {}    
    X(Y && y) :y_(std::move(y)) {}
};

是否有必要定义一个类似第二个的构造函数,以充分利用move语义?

Is it necessary to define a constructor like the second one in order to take full advantage of move semantics? Or will it be taken care of automatically in the appropriate situations?

推荐答案

是的,但没有。您的代码应该是这样:

Yes, but no. Your code should just be this:

struct X
{
    Y y_;

    X(Y y) : // either copy, move, or elide a Y
    y_(std::move(y)) // and move it to the member
    {} 
};

如果你在设计中说我需要我自己的这个数据的副本*,只需通过值取参数,并将其移动到需要的位置。决定如何构造该值,这不是你的工作,这是由该值的可用构造函数,所以让它做出这个选择,无论是什么,并使用最终结果。

If you ever say in design "I need my own copy of this data"*, then you should just take the argument by value and move it to where it needs to be. It isn't your job to decide how to construct that value, that's up to the available constructors for that value, so let it make that choice, whatever it is, and work with the end result.

*这也适用于函数,当然,例如:

*This applies to functions too, of course, for example:

void add_to_map(std::string x, int y) // either copy, move or elide a std::string
{
    // and move it to where it needs to be
    someMap.insert(std::make_pair(std::move(x), y));
}






C ++ 03也有点,如果一个类型是默认可构造和可交换的(这是所有移动都做):


Note that is applied in C++03 too, somewhat, if a type was default constructible and swappable (which is all moving does anyway):

// C++03
struct X
{
    std::string y_;

    X(std::string y) // either copy or elide a std::string
    {
        swap(y_, y); // and "move" it to the member
    } 
};

虽然这似乎并没有做得那么广泛。

Though this didn't seem to be as widely done.

这篇关于是否有必要从不同的类定义移动构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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