1 #include <QCoreApplication> 2 #include <thread> 3 #include <iostream> 4 5 6 /* 7 * 話題: 刪除函數。 8 * 函數使用 =delete 說明符。 全局函數,類成員函數均可使用。 9 * 10 * 1. 通過添加 =delete 將一個函數聲明為刪除函數。 調用被刪除的函數會引發編譯錯誤。 11 * 12 * 實例情景: 13 * 1. 杜絕對象被拷貝和賦值。 例如:std::mutex, std::unique_lock等 14 * 將拷貝構造函數和賦值運算符聲明為刪除函數。 這個時候,務必顯示的聲明移動構造函數和移動賦值運算符。我們的類只移動。 15 * 16 * 2. =delete說明符與函數重載相結合使用, 可以刪除特定的重載。 17 * 比如,void func(short); void func(int); 當我們以short作為參數, 為避免擴展為int, 可以將 void func(int) = delete 聲明為刪除函數。 18 * 19 */ 20 21 //! [0] 實例情景:-1 22 class thread_guard{ 23 public: 24 thread_guard(std::thread & t):_t(t){} 25 ~thread_guard(){ 26 if (_t.joinable()) 27 _t.join(); 28 } 29 30 thread_guard(thread_guard & other) = delete; 31 thread_guard(thread_guard &&other):_t(std::move(other._t)){} 32 33 thread_guard & operator=(thread_guard & other) = delete; 34 thread_guard & operator=(thread_guard && other){ 35 _t = std::move(other._t); 36 return *this; 37 } 38 39 private: 40 std::thread & _t; 41 }; 42 43 void hello(){ 44 std::cout<<"hello word "<<std::endl; 45 } 46 //! [0] 47 48 49 50 //! [1] 實例情景:-2 51 void func(short a){ 52 std::cout<<a<<" sizeof is "<<sizeof(a)<<std::endl; 53 } 54 #if 0 55 void func(int a){ 56 std::cout<<a<<" sizeof is "<<sizeof(a)<<std::endl; 57 } 58 #else 59 void func(int a) = delete; 60 #endif 61 62 //! [1] 63 int main(int argc, char *argv[]) 64 { 65 QCoreApplication a(argc, argv); 66 67 //! [0] 68 { 69 std::thread t(hello); 70 thread_guard _guard(t); 71 //thread_guard _guardOther(_guard); //error info: thread_guard::thread_guard(thread_guard &) 嘗試引用已刪除的函數 72 thread_guard _guardOther(std::move(_guard)); //想要移動左置, 需顯示使用 std::move 或者 static_cast<T&&>() 73 } 74 //! [0] 75 76 std::cout<<std::endl; 77 //! [1] 78 int _v = 10; 79 //func(_v); //error: void func(int) 嘗試引用已刪除的函數 80 //因 void func(int) 聲明為刪除函數,因此任何向 func傳遞整形的調用都會產生一個編譯錯誤。 81 82 func(short(_v)); //調用時可顯示的轉換 83 //! [1] 84 85 return a.exec(); 86 }
