std::addressof - cppreference.com
提供: cppreference.com
<tbody> </tbody> <tbody class="t-dcl-rev t-dcl-rev-num "> </tbody><tbody> </tbody>
| ヘッダ |
||
| (1) | ||
|
|
(C++11以上) (C++17未満) |
|
|
|
(C++17以上) | |
|
|
(2) | (C++17以上) |
1) オーバーロードされた operator& が存在していても、オブジェクトまたは関数 arg の実際のアドレスを取得します。
2) const 右辺値のアドレスを取得することを防ぐために、右辺値のオーバーロードは削除されています。
|
|
(C++17以上) |
引数
戻り値
arg を指すポインタ。
実装例
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; }
ノート: 上記の実装は constexpr ではありません (コンパイラのサポートが必要になります)。
例
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 << std::endl; } ~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