Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Why it's not the same address (pointers)

i tested some new functions of c++14 and I wondered why these pointers do not have the same address

#include <iostream>
#include <memory>

class Test
{
public  :
    Test(){std::cout << "Constructor" << std::endl;}
    Test(int val){value = val;}
    ~Test(){std::cout << "Destructor" << std::endl;}

private :
    unsigned int value;
};

int main(int argc, char *argv[])
{

    std::unique_ptr<Test> ptr(new Test(45));
    std::cout << &ptr << std::endl;

    std::unique_ptr<Test> ptr2 (std::move(ptr));
    std::cout << &ptr2 << std::endl;

        return 0;
}  


Output : 
    0xffffcbb0
    0xffffcba0 //Why it's not the same as previous 
    Destructor

Thank you :) and have a good day

like image 844
Adam Brevet Avatar asked May 19 '26 03:05

Adam Brevet


1 Answers

You are printing out the addresses of the unique_ptr variables themselves, not the addresses that they point to. Use the unique_ptr::get() method instead of the & operator:

std::unique_ptr<Test> ptr(new Test(45));
std::cout << ptr.get() << std::endl;

std::unique_ptr<Test> ptr2 (std::move(ptr));
std::cout << ptr2.get() << std::endl;
like image 137
Dani Avatar answered May 20 '26 16:05

Dani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!