跳轉到內容

更多 C++ 習語/地址運算子

來自華夏公益教科書,自由的教科書

地址運算子

[編輯 | 編輯原始碼]

查詢具有過載的一元取地址運算子 (&) 運算子的類的物件的地址。

也稱為

[編輯 | 編輯原始碼]

此習語沒有已知的別名。

C++ 允許為類型別過載一元取地址運算子 (&)。此類運算子的返回值型別不必是物件的實際地址。此類類的意圖存在爭議,但語言允許它。地址運算子是一種在不考慮過載的一元取地址運算子及其訪問保護的情況下找到物件真實地址的方法。

在下面的示例中,main 函式無法編譯,因為類 nonaddressableoperator & 是私有的。即使它可以訪問,從它的返回值型別 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

已知用途

[編輯 | 編輯原始碼]
[編輯 | 編輯原始碼]

參考文獻

[編輯 | 編輯原始碼]
  1. "The template std::addressof".
  2. "Boost addressof utility".
華夏公益教科書