问题描述
我目前正在学习智能指针,但有点困惑。为什么共享指针既不使用简单打印也不使用 get() 打印存储为原始指针的内存地址?
int x = 100;
int* y = &x;
std::cout<<&x<<std::endl;
std::cout<<y<<std::endl;
std::shared_ptr<int> x2 = std::make_shared<int>(x);
std::cout<<x2.get()<<std::endl
0x7ffe965e20b4
0x7ffe965e20b4
**0x2176c30** so why this value is for both x2.get() and x2 ?
谢谢
解决方法
x2
与 x
指向的位置不同。
std::shared_ptr<int> x2 = std::make_shared<int>(x);
这一行创建了一个指向 int 的新指针,并使用 x
的值对其进行初始化。
所以他们在这一点上唯一的共同点是指针 x
和 x2
都指向值为 100 的 int
。还有 2 个不同的 {{ 1}}虽然。