許多教材(包括《Effective C++》早期版本)聲稱空類:
class Empty {};
等價於:
class Empty {
public:
Empty();
Empty(const Empty&);
~Empty();
Empty& operator=(const Empty&);
Empty* operator&();
const Empty* operator&() const;
};
根據 ISO/IEC 14882 §12「特殊成員函數」:
operator&()(無論 const 或非 const)編譯器直接使用內建取址運算子,而非產生成員函數。這不是全域 operator& 的應用,而是語言內建行為。
作者於勘誤表確認:
A class declaring no
operator&function(s) does NOT have them implicitly declared. Rather, compilers use the built-in address-of operator whenever&is applied to an object of that type.
#include <iostream>
struct Empty {};
int main() {
Empty e;
std::cout << &e << '\n'; // 正常編譯,使用內建 operator&
// Empty::operator&() 並不存在
}
| 成員函數 | 隱式宣告 | 備註 |
|---|---|---|
| 預設建構函數 | 是 | 無使用者宣告建構函數時 |
| 拷貝建構函數 | 是 | 非刪除、非移動情況 |
| 移動建構函數 (C++11) | 條件 | 無使用者宣告拷貝/移動/解構 |
| 拷貝賦值 | 是 | |
| 移動賦值 (C++11) | 條件 | |
| 解構函數 | 是 | 非虛擬、非刪除 |
| operator&() | 否 | 使用內建運算子 |