【问题标题】:C++ Why it's not the same address (pointers)C++ 为什么它不是同一个地址(指针)
【发布时间】:2016-07-18 19:39:46
【问题描述】:

我测试了一些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

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

【问题讨论】:

  • FWIW,这是 C++11 代码。那里没有特定于 C++14 的内容。
  • 你永远不会移动变量的地址。你改变他们的价值观。

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


【解决方案1】:

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

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;

【讨论】:

  • 谢谢,但是当我执行你的代码时,ptr2的地址是0 || ptr = 0x6000284d0 , ptr2 = 0
  • 我认为是因为我的编译器
  • @AdamBrevet:第二次你仍然使用ptr 而不是ptr2ptr 已被移出,因此其值预计为 0。
  • 不太可能是编译器错误。
  • 好的,对不起,这是我的错误。其作品。谢谢你的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 2021-06-28
相关资源
最近更新 更多