更多 C++ 習語/地址運算子
外觀
查詢具有過載的一元取地址運算子 (&) 運算子的類的物件的地址。
此習語沒有已知的別名。
C++ 允許為類型別過載一元取地址運算子 (&)。此類運算子的返回值型別不必是物件的實際地址。此類類的意圖存在爭議,但語言允許它。地址運算子是一種在不考慮過載的一元取地址運算子及其訪問保護的情況下找到物件真實地址的方法。
在下面的示例中,main 函式無法編譯,因為類 nonaddressable 的 operator & 是私有的。即使它可以訪問,從它的返回值型別 double 到指標的轉換也不可能或沒有意義。
class nonaddressable
{
public:
typedef double useless_type;
private:
useless_type operator&() const;
};
int main()
{
nonaddressable na;
nonaddressable * naptr = &na; // Error: operator & of type nonadressable is private.
}
地址運算子使用一系列強制轉換來檢索物件的地址。
template <class T>
T * addressof(T & v)
{
return reinterpret_cast<T *>(& const_cast<char&>(reinterpret_cast<const volatile char &>(v)));
}
int main()
{
nonaddressable na;
nonaddressable * naptr = addressof(na); // No more compiler error.
}
在 C++11 中,模板 std::addressof[1](在 <memory> 標頭檔案中)被新增來解決這個問題。從 C++17 開始,該模板也被標記為 constexpr。