2016-05-12 92 views
0

我很好奇,爲什麼在C++ 11中,在派生虛擬方法上使用「= default」不會選擇純基類實現。C++ 11 =默認關鍵字虛擬函數指定默認的純實現

例如,以下測試代碼從「g ++ -std = C++ 11」中產生消息「error:'virtual void B :: tst()'不能默認」。

struct A { 
    virtual ~A() = default; 
    virtual void tst() = 0; 
}; 

void A :: tst() {} 

struct B : public A { 
    virtual void tst() = default; 
}; 

我們當然可以提供B :: TST調用默認的基本實現,但有擔心,這可能是更高的開銷實現比假設的「=默認」的基礎編碼。

不好意思問一下關於C++標準委員會成員可能會或可能不會想到什麼的問題,但是也許這裏的一個人在堆棧溢出問題上會有一些關於以這種方式使用默認關鍵字的不切實際的看法,聽起來很有趣。

謝謝!

+0

默認情況下,子類在不寫任何內容的情況下共享父級的實現,假設子級非私有地繼承父級。所以,在這種情況下,你想要擁有'= default'是什麼意思? – md5i

+0

當虛函數是純的時,我們需要派生類選擇一個實現。派生類可以提供實現,或者選擇調用基本中的默認實現。然而,= default可能允許派生指定只由編譯器加載到vtable中的基本默認值,與調度派生到派生實現並轉回默認基本實現相比,這可能更有效。不過,我認爲這是讓派生類在編譯時選擇的重要設計選擇。 –

回答

1

根據標準§8.4.2/ P1顯式默認的功能[dcl.fct.def.default]重點礦山):

A function definition of the form:

attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt = default;

is called an explicitly-defaulted definition. A function that is explicitly defaulted shall

(1.1) — be a special member function,

(1.2) — have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be 「reference to non-const T」, where T is the name of the member function’s class) as if it had been implicitly declared, and

(1.3) — not have default arguments

成員函數tst()不是special member function 。因此,它不能被默認。

現在將類的成員函數(例如,class A)指定爲純虛擬需要從該類繼承的任何類,並且您也不希望它是抽象類,必須重寫該成員函數。

+0

好吧,標準說這種類型的純粹的基類默認實現選擇行爲不支持,但不過人們好奇它爲什麼沒有 –