std::addressof
提供: cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| ヘッダ <memory> で定義
|
||
| (1) | ||
template< class T > T* addressof(T& arg) noexcept; |
(C++11以上) (C++17未満) |
|
template< class T > constexpr T* addressof(T& arg) noexcept; |
(C++17以上) | |
template <class T> const T* addressof(const T&&) = delete; |
(2) | (C++17以上) |
1) オーバーロードされた
operator& が存在していても、オブジェクトまたは関数 arg の実際のアドレスを取得します。2)
const 右辺値のアドレスを取得することを防ぐために、右辺値のオーバーロードは削除されています。|
|
(C++17以上) |
引数
| arg | - | 左辺値のオブジェクトまたは関数 |
戻り値
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& はポインタへのポインタを取得するためにポインタラッパークラスに対してオーバーロードされているかもしれません。
Run this code
#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
関連項目
| デフォルトのアロケータ (クラステンプレート) | |
[静的] |
引数を指す逆参照可能なポインタを取得します ( std::pointer_traits<Ptr>のパブリック静的メンバ関数)
|