2010-09-13 61 views
7

這兩行奇怪的代碼是什麼意思?什麼是「=刪除」?

thread_guard(thread_guard const&) = delete; 

thread_guard& operator=(thread_guard const&) = delete; 

回答

11

=delete是C++ 0x的新功能。這意味着一旦用戶使用這種功能,編譯器應該立即停止編譯並且抱怨「該函數被刪除」(參見Bjarne Stroustrup的C++ 0x FAQ的defaulted and deleted functions -- control of defaults)。

thread_guard(thread_guard const&)是一個拷貝構造函數,而thread_guard& operator=(thread_guard const&)是一個賦值構造函數。因此這兩條線共同禁用了thread_guard實例的複製。

+1

差不多。在未評估的上下文中「使用」刪除的函數(例如,作爲「decltype」的表達式)可以作爲模板參數推理失敗。這使編譯器忽略模板。它不會使編譯器停止編譯。 – sellibitze 2010-09-13 20:34:20

10

這是用於禁用類的某些功能的新的C++ 0x語法。一個例子見wikipedia。在這裏,您告訴類thread_guard既不可複製也不可分配。

+0

它也適用於其他功能。 – sellibitze 2010-10-18 19:53:59