应该将移动语义用于构造函数链中吗? [英] Should move semantics be used in constructor chains?

查看:104
本文介绍了应该将移动语义用于构造函数链中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个类:

class Person
{
    public:
        Person(string name, string surname)
            : _name(move(name)), _surname(move(surname)) { }
        ...
    private:
        string _name;
        string _surname;
};

class Student : public Person
{
    public:
        Student(string name, string surname, Schedule schedule)
            : Person(move(name), move(surname)), _schedule(move(schedule)) { }
        ...
    private:
        Schedule _schedule;
};

int main()
{
    Student s("Test", "Subject", Schedule(...));
    ...
    return 0;
}

这是移动语义的好用法吗?如你所见,在Student构造函数中有一个'move-s'层。是否可以避免 move 函数调用开销,而不使用 const 引用将参数转发给基础构造函数?

Is that a good usage of move semantics? As you can see there's a layer of 'move-s' in the Student constructor. Is it possible to avoid the move function call overhead without using const references to forward the parameters to the base constructor?

或者,当我需要将参数转发给基础构造函数时,我应该使用const引用。

Or perhaps..should I be using const references whenever I need to forward parameters to the base constructor?

推荐答案

否。对于非常大的类型(这种类型很少),您只能获得性能提升。当然,当你处理一些你事先不知道的类型是非常昂贵的移动或不可移动,然后采取廉价的举动。

No. You will only get a performance improvement for types which are of a very large size, which is very rare. Absolutely, when dealing with some type which you don't know in advance is very expensive to move, or immovable, then assume cheap moves.

你现有的代码是惯用的C ++ 11,并且在这方面一个完美的转发构造函数是错误的,并且将讽刺地打破一个参数启动的东西。

Your existing code is idiomatic C++11, and a perfect forwarding constructor in this respect is wrong and will hideously break things for one parameter to boot.

这篇关于应该将移动语义用于构造函数链中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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