Adam Brevet
Adam Brevet

Reputation: 37

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

Upvotes: 2

Views: 372

Answers (1)

Daniel
Daniel

Reputation: 31579

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;

Upvotes: 16

Related Questions