如何理解智能指针的底层指针地址?
How to understand the underlying pointer address of a smart pointer?
我正在攻读 Udacity 的 C++ 纳米学位,讲座中有一些关于智能指针的内容,我认为这是一个错误,或者我遗漏了什么。
考虑以下示例:
#include <iostream>
#include <memory>
#include <string>
class MyClass
{
private:
std::string _text;
public:
MyClass() {}
MyClass(std::string text) { _text = text; }
~MyClass() { std::cout << _text << " destroyed" << std::endl; }
void setText(std::string text) { _text = text; }
};
int main()
{
// create unique pointer to proprietary class
std::unique_ptr<MyClass> myClass1(new MyClass());
std::unique_ptr<MyClass> myClass2(new MyClass("String 2"));
// call member function using ->
myClass1->setText("String 1");
// use the dereference operator *
*myClass1 = *myClass2;
---This is the part I don't understand---
// use the .get() function to retrieve a raw pointer to the object
std::cout << "Objects have stack addresses " << myClass1.get() << " and " << myClass2.get() << std::endl;
return 0;
}
我是这样理解这个例子的:
他们使用 unique_ptr's get method 获取指向托管数据的指针,该数据分配在堆上。所以这个地址应该是堆地址,不是内部指针所在的栈地址。 (智能指针的内部原始指针的堆栈地址应该不能从外部访问吧?)
官方对这段代码的解释是:"Obviously, both pointers have different addresses on the stack, even after copying the contents from myClass2 to myClass1."
但它不应该这样说吗:"Both pointers still point to their respective heap addresses, only the data has been copied from one address to the other"?
正确。 unique_ptr
objects 有不同的堆栈地址,它们也指向不同的堆地址。
做类似 myClass1.reset(myClass2.get())
的事情会使两个 unique_ptr
对象指向同一个堆地址,这是对 unique_ptr
不变量的严重违反。
我正在攻读 Udacity 的 C++ 纳米学位,讲座中有一些关于智能指针的内容,我认为这是一个错误,或者我遗漏了什么。 考虑以下示例:
#include <iostream>
#include <memory>
#include <string>
class MyClass
{
private:
std::string _text;
public:
MyClass() {}
MyClass(std::string text) { _text = text; }
~MyClass() { std::cout << _text << " destroyed" << std::endl; }
void setText(std::string text) { _text = text; }
};
int main()
{
// create unique pointer to proprietary class
std::unique_ptr<MyClass> myClass1(new MyClass());
std::unique_ptr<MyClass> myClass2(new MyClass("String 2"));
// call member function using ->
myClass1->setText("String 1");
// use the dereference operator *
*myClass1 = *myClass2;
---This is the part I don't understand---
// use the .get() function to retrieve a raw pointer to the object
std::cout << "Objects have stack addresses " << myClass1.get() << " and " << myClass2.get() << std::endl;
return 0;
}
我是这样理解这个例子的: 他们使用 unique_ptr's get method 获取指向托管数据的指针,该数据分配在堆上。所以这个地址应该是堆地址,不是内部指针所在的栈地址。 (智能指针的内部原始指针的堆栈地址应该不能从外部访问吧?)
官方对这段代码的解释是:"Obviously, both pointers have different addresses on the stack, even after copying the contents from myClass2 to myClass1."
但它不应该这样说吗:"Both pointers still point to their respective heap addresses, only the data has been copied from one address to the other"?
正确。 unique_ptr
objects 有不同的堆栈地址,它们也指向不同的堆地址。
做类似 myClass1.reset(myClass2.get())
的事情会使两个 unique_ptr
对象指向同一个堆地址,这是对 unique_ptr
不变量的严重违反。