📜  C++中的std :: to_address及其示例

📅  最后修改于: 2021-05-30 04:49:16             🧑  作者: Mango

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

输出:

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

范例2:

// C++ code to show
// the use of std::address
  
#include 
#include 
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(15);
    cout << "Address of pointer to 15: "
         << to_address(ptr) << "\n";
  
    auto ptr1 = make_unique(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

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”