std::to_address in C++ with example

Hi there. Today we will see the working of the “to_address” method of STL library in C++. The purpose of this method is to get the address of a specific pointer without creating a reference to the pointer. The parameter it takes is a fancy or raw pointer. And it returns the same address as the passed parameter. Also, this program will only run with compiler “GCC 9.2”, or above versions. If you want to use it for other versions, you will need to create a template of the to_address method, and then you can use it. Now, let’s see the program.

C++ std::to_address

First, we are going to create a unique pointer and use the to_address method to get the address from heap memory. We are making two of them, for your better understanding. As you will see, the to_address method prints the address. Next, we are going to it for dumb pointers. Again, we will see two examples of it. Now, let’s look at the code.

#include<iostream>
#include<memory>
using namespace std; 

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

int main() 
{ 
    cout<<"With unique pointers"<<endl; 
    auto p=make_unique<int>(20); 
    cout<<"Address of pointer p is-"<<to_address(p)<<endl;
    auto p2=make_unique<int>(22); 
    cout<<"Address of pointer p2 is-"<<to_address(p2)<<endl; 
  
    cout<<endl;

    int i=20; 
    cout<<"Address of the pointer to 20 is-"<<to_address(&i)<<endl; 

    int j=21;
    cout<<"Address of the pointer to 21 is-"<<to_address(&j)<<endl;
    return 0; 
}

As I said, you have to define templates for methods your compiler doesn’t recognize.

Now let’s look at the output. I will remove the template from my code when running. Because sometimes the method can become ambiguous because of templates.

With unique pointers
Address of pointer p is-0xf3ac30
Address of pointer p2 is-0xf3ac50

Address of the pointer to 20 is-0x7ffc63fb31b8
Address of the pointer to 21 is-0x7ffc63fb31bc

Now, if you get a different value for the address when you compile and run the program, don’t worry. Memory management stores the values in different addresses. It is not necessary it stores the value at the same address.

I hope you find this article useful. For further practice, you can other methods like the pointer_traits. That will enhance your grasp on the topic. Or you can see how to create and work with templates. It is a very simple, but powerful C++ tool.

Also read: std::bitset::bitset in C++

Leave a Reply

Your email address will not be published.