2013-03-16 64 views
2

假设我有以下两类:应该在构造函数链中使用移动语义吗?

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引用将参数转发给基础构造函数?

或者perhaps..should我使用常量引用每当我需要的参数转发给基构造函数?

回答

4

号你只会得到这是一个非常大的尺寸,这是非常罕见类型的性能改进。当然,在处理某种你事先不知道的类型是非常昂贵的移动或不可移动的情况下,然后假设便宜的移动。

现有的代码是地道的C++ 11,并在这方面一个完美的转发构造函数是错误的,将令人发指的破事了一个参数来启动。

+0

来自Going Native 2012的OP良好视频 - [STL11:Magic && Secrets](http://channel9.msdn.com)/Events/GoingNative/GoingNative-2012/STL11-Magic-Secrets) - 请看33:45分数值与参考值的传递。 – 2013-03-16 14:18:18

+0

@CaptainObvlious会做。谢谢。 – 2013-03-17 12:25:00

2

考虑选择以优化之前有利于代码的可读性和简单性。很可能您并不需要保存一次复制/移动操作,在这种情况下,您应该赞成清晰和简单(例如参考const)。

这就是说,如果你担心转发你的构造函数的自变量的开销,你可以让你的一个构造模板和使用完美转发招致最小的开销无论你是路过右值或左值:

class Person 
{ 
    public: 
     template<typename T, typename U> 
     Person(T&& name, U&& surname) 
      : _name(std::forward<T>(name)), _surname(std::forward<U>(surname)) { } 
     ... 
    private: 
     string _name; 
     string _surname; 
}; 

class Student : public Person 
{ 
    public: 
     template<typename T, typename U, typename V> 
     Student(T&& name, U&& surname, V&& schedule) 
      : Person(
       std::forward<T>(name), 
       std::forward<U>(surname)), 
       _schedule(std::forward<V>(schedule)) 
     { } 
     ... 
    private: 
     Schedule _schedule; 
}; 
+2

这比老派的,简单的方式更好吗? – 2013-03-16 12:47:31

+0

@JohnZwinck:它避免了不必要的复制/移动 – 2013-03-16 12:48:12

+0

@JohnZwinck除了什么安迪只是说,这样可以节省您提供'常量T&','T &&的所有组合'多参数的构造函数。 – juanchopanza 2013-03-16 12:49:25

相关问题