C++ 为什么它不是同一个地址(指针)

标签 c++ c++11 pointers smart-pointers

我测试了一些c++14的新函数,我想知道为什么这些指针没有相同的地址

#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

谢谢 :) 祝你有美好的一天

最佳答案

您正在打印出 unique_ptr 变量本身的地址,而不是它们指向的地址。使用 unique_ptr::get()方法而不是 & 运算符:

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;

关于C++ 为什么它不是同一个地址(指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38444723/

相关文章:

c++ - 无法通过 Linux 上的 FreeTDS bcp API 将 DATE 插入 mssql

c++ - 在 switch 语句中从 int 到 enum 类的隐式转换

c++ - 双簧管异步音频提取

c++ - 在类模板中创建映射元组

c++ - 为什么 shared_ptr 签名与数组的 unique_ptr 不同?

c++ - 使用数组的段错误

c - 双指针取消引用的段错误

java - 将对象添加到 Java 集合时,是按值添加还是按引用添加?

c++ - 如何初始化一个类数据成员,它是一个带有自定义比较器的 std::set

c++ - 用于 IVR 应用的 SIP RTP 栈