最終更新日時(UTC):
が更新

履歴 編集

function template
<memory>

std::addressof(C++11)

namespace std {
  template <class T>
  T* addressof(T& r) noexcept;                 // (1) C++11

  template <class T>
  constexpr T* addressof(T& r) noexcept;       // (1) C++17

  template <class T>
  const T* addressof(const T&& elem) = delete; // (2) C++17
}

概要

変数のアドレスを必ず取得する。

operator&() をオーバーロードしたクラスであっても、正しくそのオブジェクトのアドレスが欲しいという要求がある。

addressof()関数は、operator&() がオーバーロードされていても、変数のアドレスを取得できる。

戻り値

変数rのアドレスを返す。

例外

投げない

備考

  • (2) : このオーバーロードは、addressof<const int>(0)のような明示的型指定によって一時オブジェクトのアドレス取得ができてしまう問題を回避するためのもの

#include <memory>
#include <iostream>

struct useless_type {};

// operator&がオーバーロードされたクラス
class nonaddressable {
public:
  useless_type operator&() const { return useless_type(); }
};

int main()
{
  {
    int x = 3;
    int* p1 = std::addressof(x); // OK : アドレス取得できる
    int* p2 = &x; // OK : アドレス取得できる
  }
  {
    nonaddressable x;
    nonaddressable* p1 = std::addressof(x); // OK : アドレス取得できる
//  nonaddressable* p2 = &x; // エラー!アドレス取得できない
  }
}

出力

バージョン

言語

  • C++11

処理系

  • Clang: ??
  • GCC: 4.7.0
  • ICC: ??
  • Visual C++: 2012, 2013
    • 2012はマニュアル(MSDNライブラリ)に記載がないものの、実装されている。

参照