名前空間
変種
操作

std::to_address

提供: cppreference.com
< cpp‎ | memory
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
動的メモリ管理
スマートポインタ
(C++11)
(C++11)
(C++11)
(C++17未満)
(C++11)
アロケータ
メモリリソース
未初期化記憶域
ガベージコレクションサポート
その他
to_address
(C++20)
(C++11)
(C++11)
C のライブラリ
低水準のメモリ管理
 
ヘッダ <memory> で定義
template< class Ptr >
constexpr auto to_address(const Ptr& p) noexcept;
(1) (C++20以上)
template< class T >
constexpr T* to_address(T* p) noexcept;
(2) (C++20以上)

指す先への参照を形成せずに p の表すアドレスを取得します。

1) ファンシーポインタのオーバーロード。 式 std::pointer_traits<Ptr>::to_address(p) が well-formed であれば、その式の結果を返します。 そうでなければ、 std::to_address(p.operator->()) を返します。
2) 生のポインタのオーバーロード。 T が関数型の場合、プログラムは ill-formed です。 そうでなければ、 p を変更せずに返します。

目次

[編集] 引数

p - ファンシーポインタまたは生のポインタ

[編集] 戻り値

p が表すのと同じアドレスを表す名前のポインタ。

[編集] 実装例

template<class T>
constexpr T* to_address(T* p) noexcept
{
    static_assert(!std::is_function_v<T>);
    return p;
}
 
template<class T>
constexpr auto to_address(const T& p) noexcept
{
    if constexpr (requires{ std::pointer_traits<T>::to_address(p); }) {
        return std::pointer_traits<T>::to_address(p);
    } else {
        return std::to_address(p.operator->());
    }
}

[編集] ノート

std::to_addressp がオブジェクトの構築された記憶域を参照しないときでも使用することができます。 この場合、 std::addressof の引数を束縛するのための有効なオブジェクトが存在しないため、 std::addressof(*p) は使用できません。

[編集]

#include <memory>
 
template<class A>
auto allocator_new(A& a)
{
    auto p = a.allocate(1);
    try {
        std::allocator_traits<A>::construct(a, std::to_address(p));
    } catch (...) {
        a.deallocate(p, 1);
        throw;
    }
    return p;
}
 
template<class A>
void allocator_delete(A& a, typename std::allocator_traits<A>::pointer p)
{
    std::allocator_traits<A>::destroy(a, std::to_address(p));
    a.deallocate(p, 1);
}
 
int main()
{
    std::allocator<int> a;
    auto p = allocator_new(a);
    allocator_delete(a, p);
}


[編集] 関連項目

ポインタライクな型に関する情報を提供します
(クラステンプレート) [edit]
[静的] (C++20)
ファンシーポインタから生のポインタを取得します (pointer_to の逆)
(std::pointer_traits<Ptr>のパブリック静的メンバ関数) [edit]