std::addressof
來自 cppreference.com
定義於標頭檔案 <memory> |
||
template< class T > T* addressof( T& arg ) noexcept; |
(1) | (C++11 起) (自 C++17 起為 constexpr) |
template< class T > const T* addressof( const T&& ) = delete; |
(2) | (C++11 起) |
1) 獲取物件或函式 arg 的實際地址,即使存在過載的 operator&。
2) 右值過載被刪除以防止獲取 const 右值的地址。
表示式 |
(C++17 起) |
目錄 |
[編輯] 引數
arg | - | 左值物件或函式 |
[編輯] 返回值
指向 arg 的指標。
[編輯] 可能實現
下面的實現不是 constexpr,因為 reinterpret_cast 不能用於常量表達式。需要編譯器支援(見下文)。
template<class T> typename std::enable_if<std::is_object<T>::value, T*>::type addressof(T& arg) noexcept { return reinterpret_cast<T*>( &const_cast<char&>( reinterpret_cast<const volatile char&>(arg))); } template<class T> typename std::enable_if<!std::is_object<T>::value, T*>::type addressof(T& arg) noexcept { return &arg; } |
此函式的正確實現需要編譯器支援:GNU libstdc++、LLVM libc++、Microsoft STL。
[編輯] 注意
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_addressof_constexpr |
201603L |
(C++17) | constexpr std::addressof |
addressof
的 constexpr 由 LWG2296 新增,MSVC STL 將此更改作為缺陷報告應用於 C++14 模式。
在某些奇怪的情況下,由於實參依賴查詢,即使內建的 operator& 沒有被過載,其使用仍然是病態的,此時可以使用 std::addressof
代替。
template<class T> struct holder { T t; }; struct incomp; int main() { holder<holder<incomp>*> x{}; // &x; // error: argument-dependent lookup attempts to instantiate holder<incomp> std::addressof(x); // OK }
[編輯] 示例
operator& 可以為指標包裝類過載,以獲取指向指標的指標
執行此程式碼
#include <iostream> #include <memory> template<class T> struct Ptr { T* pad; // add pad to show difference between 'this' and 'data' T* data; Ptr(T* arg) : pad(nullptr), data(arg) { std::cout << "Ctor this = " << this << '\n'; } ~Ptr() { delete data; } T** operator&() { return &data; } }; template<class T> void f(Ptr<T>* p) { std::cout << "Ptr overload called with p = " << p << '\n'; } void f(int** p) { std::cout << "int** overload called with p = " << p << '\n'; } int main() { Ptr<int> p(new int(42)); f(&p); // calls int** overload f(std::addressof(p)); // calls Ptr<int>* overload, (= this) }
可能的輸出
Ctor this = 0x7fff59ae6e88 int** overload called with p = 0x7fff59ae6e90 Ptr overload called with p = 0x7fff59ae6e88
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2598 | C++11 | std::addressof<const T> 可以獲取右值的地址 | 被已刪除的過載停用 |
[編輯] 參閱
預設分配器 (類模板) | |
[靜態] |
獲取指向其引數的可解引用指標 ( std::pointer_traits<Ptr> 的公共靜態成員函式) |