std::addressof
From 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) operator& のオーバーロードが存在する場合でも、オブジェクトまたは関数 arg の実際のメモリアドレスを取得します。
2) 右辺値オーバーロードは、const 右辺値のアドレス取得を防止するために削除されます。
|
e が左辺値の定数部分式である場合、式 |
(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++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 2598 | C++11 | std::addressof<const T> は右辺値のアドレスを取る可能性があります。 | 削除されたオーバーロードによって禁止されています。 |
[編集] 関連項目
| デフォルトアロケータ (クラステンプレート) | |
| [static] |
引数への逆参照可能なポインターを取得する ( std::pointer_traits<Ptr> の公開静的メンバ関数) |