std::to_address
提供: cppreference.com
ヘッダ <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_address
は p
がオブジェクトの構築された記憶域を参照しないときでも使用することができます。 この場合、 std::addressof の引数を束縛するのための有効なオブジェクトが存在しないため、 std::addressof(*p) は使用できません。
[編集] 例
Run this code
#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); }
[編集] 関連項目
(C++11) |
ポインタライクな型に関する情報を提供します (クラステンプレート) |
[静的] (C++20) |
ファンシーポインタから生のポインタを取得します (pointer_to の逆) ( std::pointer_traits<Ptr> のパブリック静的メンバ関数)
|