當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::to_address用法及代碼示例

C++ 20中引入的std::to_address用於獲取由指定指針表示的地址,而不形成對指針的引用。現有的std::addressof無法執行std::addressof( * ptr),因為* ptr並不總是對象。 std::to_address為我們解決了這些問題。

用法:

template class Ptr
constexpr auto to_address(const Ptr& p) noexcept;

template class T
constexpr T* to_address(T* p) noexcept;

參數:此方法接受參數p,該參數是要查找其地址的奇特或原始指針。

返回值:此方法返回代表指針p地址的Raw指針。

以下示例演示了std::address的用法
例子1



// C++ code to show 
// the use of std::address 
  
#include <iostream> 
#include <memory> 
using namespace std; 
  
// Allocate memory and return 
// the pointer to that memory 
template <class A> 
auto allocator_new(A& a) 
{ 
    auto p = a.allocate(1); 
    try { 
        allocator_traits<A>::construct( 
            a, to_address(p)); 
    } 
    catch (...) { 
        a.deallocate(p, 1); 
        throw; 
    } 
  
    cout << "Pointer to Memory allocated:"
         << p << endl; 
    return p; 
} 
  
// Delete memory using 
// pointer to that memory 
template <class A> 
void allocator_delete( 
    A& a, 
    typename allocator_traits<A>::pointer p) 
{ 
    allocator_traits<A>::destroy( 
        a, to_address(p)); 
    a.deallocate(p, 1); 
    cout << "Pointer to Memory deleted:"
         << p << endl; 
} 
  
// Driver code 
int main() 
{ 
    allocator<int> a; 
    auto p = allocator_new(a); 
    allocator_delete(a, p); 
}

輸出:

Pointer to Memory allocated:0x1512c20
Pointer to Memory deleted:0x1512c20

範例2:

// C++ code to show 
// the use of std::address 
  
#include <iostream> 
#include <memory> 
using namespace std; 
  
int main() 
{ 
  
    // Make a unique pointer and 
    // use to_address to get its address 
    // from heap memory 
    cout << "Using unique pointers\n\n"; 
    auto ptr = make_unique<int>(15); 
    cout << "Address of pointer to 15:"
         << to_address(ptr) << "\n"; 
  
    auto ptr1 = make_unique<int>(17); 
    cout << "Address of pointer to 17:"
         << to_address(ptr1) << "\n"; 
  
    // Use to_address to get the 
    // address of a dumb pointer 
    // from stack memory 
    cout << "\nUsing dumb pointers\n\n"; 
  
    int i = 17; 
    cout << "Address of pointer to 17:"
         << to_address(&i) << "\n"; 
  
    int j = 18; 
    cout << "Address of pointer to 18:"
         << to_address(&j) << "\n"; 
  
    return 0; 
}

輸出:

Using unique pointers

Address of pointer to 15:0x181ec30
Address of pointer to 17:0x181ec50

Using dumb pointers

Address of pointer to 17:0x7fff6b454398
Address of pointer to 18:0x7fff6b45439c

參考: https://en.cppreference.com/w/cpp/memory/to_address




相關用法


注:本文由純淨天空篩選整理自soham1234大神的英文原創作品 std::to_address in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。