C++ nocopyable 原

有時候我們要求某些類不能被拷貝,我們可以通過實現,一個不可拷貝的父類,子類對象繼承父類對象,來達到子類對象不可拷貝的目的。 
實現一個不可拷貝對象就是把拷貝構造函數和賦值運算符聲明爲私有的,同時實現構造函數(必須有,由於提供了拷貝構造,編譯器不在提供)和析構函數。因此我們把nocopyable實現如下:

#ifndef NOCOPYABLE_H
#define NOCOPYABLE_H

class nocopyable {
protected:
  nocopyable(){};
  ~nocopyable(){};
private:
  nocopyable(const nocopyable& that);
  nocopyable& operator=(const nocopyable& that);
};

#endif //NOCOPYABLE_H

測試代碼如下:

#include <iostream>
#include "nocopyable.h"

using namespace std;
//私有繼承就可以
class nocopy : nocopyable {
};

int main() {
  nocopy no1;
//  nocopy no2 = no1;
  return 0;
}

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。

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