1

我正在寫我自己的矢量類(x,y值的容器),我不確定我應該自己實現哪些構造函數/賦值運算符,以及我可以指望編譯器提供什麼。很顯然,我需要編寫任何沒有默認行爲或者在任何情況下都不會自動生成的方法。但是肯定的是,如果編譯器可以生成完全相同的東西,那麼實現它也沒有意義。矢量類應該有什麼ctor /賦值運算符?

我正在使用Visual Studio 2010(這可能在C++ 11方面很重要)。如果那很重要,我的課也是模板課。

目前,我有:

template <typename T> 
class Integral2 
{ 
    // ... 

    Integral2(void) 
     : x(0), y(0) 
    {} 

    Integral2(Integral2 && other) 
     : x(std::move(other.x)), y(std::move(other.y)) 
    {} 

    Integral2(T _x, T _y) 
     : x(_x), y(_y) 
    {} 

    Integral2 & operator =(Integral2 const & other) 
    { 
     x = other.x; 
     y = other.y; 
     return *this; 
    } 

    Integral2 & operator =(Integral2 && other) 
    { 
     x = std::move(other.x); 
     y = std::move(other.y); 
     return *this; 
    } 

    // ... 
}; 

我需要拷貝構造函數/賦值運算符時,我有一招構造函數/移動運營商?

回答

1

在C++中,有Rule of Three,它提供了您應該根據哪些構造函數/操作符定義您需要的基礎的指導原則。在C++ 11中,有些人認爲移動語義將三條規則推到become the rule of five。有關示例實現,請參閱this thread。我建議你看看這些指導方針。