編譯器默認為一個類生成的默認函數
- 默認構造函數
- 默認析構函數
- 默認拷貝構造函數
- 默認賦值函數
- 移動構造函數
- 移動拷貝函數
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 };
=delete
1. 禁止使用編譯器默認生成的函數
假如上面的幾個函數中,不想使用其中某個,可以將其定義為private
,或者使用=delete
。
#include <iostream> using namespace std; class DataOnly { public: DataOnly () {} ~DataOnly () {} DataOnly (const DataOnly & rhs) = delete; //禁止使用該函數 DataOnly & operator=(const DataOnly & rhs) = delete; //禁止使用該函數 DataOnly (const DataOnly && rhs) {} DataOnly & operator=(DataOnly && rhs) {} }; int main(int argc, char *argv[]) { DataOnly data1; DataOnly data2(data1); // error: call to deleted constructor of 'DataOnly' DataOnly data3 = data1; // error: call to deleted constructor of 'DataOnly' return 0; }
2. delete 關鍵字可用於任何函數,不僅僅局限於類的成員函數
#include <iostream> using namespace std; class DataOnly { public: void fun(int a) {} void fun(float a) = delete; }; int main(int argc, char *argv[]) { DataOnly data1; data1.fun(1); // OK data1.fun(0.5); // error: call to member function 'fun' is ambiguous return 0; }
3. 模板特化:在模板特例化中,可以用delete來過濾一些特定的形參類型
例如:Widget 類中聲明了一個模板函數,當進行模板特化時,要求禁止參數為 void* 的函數調用。
1. 按照私有不實現
思路,應該是將特例化的函數聲明為私有型,如下:
#include <iostream> using namespace std; class Widget { public: template<typename T> void ProcessPointer(T* ptr) { cout << typeid (T).name() << endl; } private: void ProcessPointer(void*) { cout << "void" << endl; } }; int main(int argc, char *argv[]) { Widget w; int* ip = NULL; w.ProcessPointer(ip); void* vp = NULL; w.ProcessPointer(vp); //error: 'ProcessPointer' is a private member of 'Widget' w.ProcessPointer(vp); return 0; }
- =delete直接添加在后面就可以解決這個問題
= default
在程序員重載了自己上面提到的C++編譯器默認生成的函數之后,C++編譯器將不在生成這些函數的默認形式。
但是C++允許我們使用=default來要求編譯器生成一個默認函數,如
struct Point { Point()=default; Point(int _x, int _y) : x(_x), y(_y) {} int x = 0; int y = 0; }
這樣相當於無參的構造函數也是可以使用的
本文轉自:https://blog.csdn.net/lmb1612977696/article/details/80035487