C++11 之 delete 和 default

1  特殊成員函數

  設計一個類,沒有成員函數 (member function),只有數據成員 (member data)

class DataOnly {
private:
    std::string  strName;  // member data
    int         iData;
};

C++98 編譯器會隱式的產生四個函數:缺省構造函數,析構函數拷貝構造函數 拷貝賦值算子,它們被稱爲特殊成員函數 (special member function)。

在 C++11 中,被稱爲 “特殊成員函數” 的還有兩個移動構造函數 移動賦值算子

class DataOnly {
public:
    DataOnly ()                  // default constructor
    ~DataOnly ()                 // destructor

    DataOnly (const DataOnly & rhs)              // copy constructor
    DataOnly & operator=(const DataOnly & rhs)    // copy assignment operator

    DataOnly (const DataOnly && rhs)         // C++11, move constructor
    DataOnly & operator=(DataOnly && rhs)    // C++11, move assignment operator
};

2  禁止編譯器合成函數

  作爲開發者,如果不想讓用戶使用某個類成員函數,不聲明該函數即可;但對於特殊成員函數,則是另一種情況。例如,設計一個樹葉類,如下所示:

class LeafFromTree{ ... };

  萊布尼茨說過,“世上沒有兩片完全相同的樹葉” (Es gibt keine zwei Blätter, die gleich bleiben),因此,對於一片獨一無二的樹葉,下面的操作是錯誤的。

LeafFromTree  leaf1;
LeafFromTree  leaf2;
LeafFromTree  Leaf3(Leaf1);     // attempt to copy Leaf1 — should not compile!
Leaf1 = Leaf2;                  // attempt to copy Leaf2 — should not compile!

  由以上代碼可知,此時需要避免使用 “拷貝構造函數” 和 “拷貝賦值算子”

2.1  私有+不實現

  C++98 中,可聲明這些特殊成員函數爲私有型 (private),且不實現該函數,具體如下:

class LeafFromTree{
private:
    LeafFromTree( const LeafFromTree& );           // not defined
    LeafFromTree & operator=( const LeafFromTree& );    // not defined
};

  程序中如果調用了 LeafFromTree 類的拷貝構造函數 (或拷貝賦值操作符),則在編譯時,會出現鏈接錯誤 (link-time error)

  爲了將報錯提前到編譯時 (compile time),可增加了一個基類 Uncopyable,並將拷貝構造函數和拷貝賦值算子聲明爲私有型

class Uncopyable {
protected:            
    Uncopyable() {}    // allow construction and destruction of derived objects...
    ~Uncopyable() {} 
private:
    Uncopyable(const Uncopyable&);  // ...but prevent copying
    Uncopyable& operator=(const Uncopyable&);
};

 而 LeafFromTree 則私有繼承自 Uncopyable 基類

// class no longer declares copy ctor or copy assign operator
class LeafFromTree: private Uncopyable { };

2.2  delete 關鍵字

  C++11 中,可在想要 “禁止使用” 的函數聲明後加 “= delete”,而需要保留的加 "= default" 或者不採取操作

class LeafFromTree{
public:
  LeafFromTree() = default;
  ~LeafFromTree() = default;

  LeafFromTree( const LeafFromTree& ) = delete;  // mark copy ctor or copy assignment operator as deleted functions
  LeafFromTree & operator=( const LeafFromTree &) = delete; 
};

3  delete 的擴展

  C++11 中,delete 關鍵字可用於任何函數,不僅僅侷限於類成員函數

3.1  函數重載

  在函數重載中,可用 delete 來濾掉一些函數的形參類型,如下:

bool isLucky(int number);        // original function
bool isLucky(char) = delete;     // reject chars
bool isLucky(bool) = delete;     // reject bools
bool isLucky(double) = delete;   // reject doubles and floats

  這樣在調用 isLucky 函數時,如果參數類型不對,則會出現錯誤提示

if (isLucky('a')) …     // error !    call to deleted function
if (isLucky(true)) …    // error !
if (isLucky(3.5)) …     // error !

3.2  模板特化

  在模板特例化中,也可以用 delete 來過濾一些特定的形參類型。

  例如,Widget 類中聲明瞭一個模板函數,當進行模板特化時,要求禁止參數爲 void* 的函數調用。

  如果按照 C++98 的 “私有不實現“ 思路,應該是將特例化的函數聲明爲私有型,如下所示:

class Widget {
public:
    template<typename T>
    void processPointer(T* ptr) { … }
private:
    template<>             
    void processPointer<void>(void*);    // error!
};

問題是,模板特化應該被寫在命名空間域 (namespace scope),而不是類域 (class scope),因此,該方法會報錯。

  而在 C++11 中,因爲有了 delete 關鍵字,則可以直接在類域外,將特例化的模板函數聲明爲 delete, 如下所示:

class Widget {
public:
    template<typename T>
    void processPointer(T* ptr) { … }
};

template<> 
void Widget::processPointer<void>(void*) = delete; // still public, but deleted

這樣,當程序代碼中,有調用 void* 作形參的 processPointer 函數時,則編譯時就會報錯。

 

小結:

1)  Prefer deleted functions to private undefined ones

2)  Any function may be deleted, including non-member functions and template instantiations







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章