简体   繁体   English

C ++中的自动指针(auto_ptr)

[英]Auto Pointer in C++ (auto_ptr)

I am trying to figure out what this piece of code prints but I couldn't output it for some reason, it gave me an error: "1 [main] Q1c 5752 open_stackdumpfile: Dumping stack trace to Q1c.exe.stackdump". 我试图弄清楚这段代码的输出,但是由于某种原因我无法输出,它给了我一个错误:“ 1 [main] Q1c 5752 open_stackdumpfile:将堆栈跟踪信息转储到Q1c.exe.stackdump”。

double *dp=new double(1.2);
auto_ptr <double> autodp1(dp);
auto_ptr <double> autodp2=autodp1;
cout<<*autodp1<<endl;

I just want to know what it will print, if it even prints. 我只想知道它什至会打印出来。

Notice: this question was in past exam paper, just for revision. 注意:这个问题在过去的试卷中,仅供修订。

The code *autodp1 is effectively a dereferencing of a null pointer. 代码*autodp1实际上是对空指针的取消引用。 Therefore the code exhibits undefined behavior. 因此,该代码表现出未定义的行为。

You first construct autodp1 to point to the newly allocated double . 首先,构造autodp1指向新分配的double But then the constructor of autodp2 takes the owned memory for itself and sets autodp1 to null. 但是,然后autodp2的构造函数autodp2获取了拥有的内存,并将autodp1设置为null。

That's becouse the operator assignement of auto_ptr takes's the ownership (move) the pointer 这是因为auto_ptr的运算符分配采用了指针的所有权(移动)

Take a read on Wiki, it's quite good general explanation: 在Wiki上阅读,这是一个很好的一般解释:

http://en.wikipedia.org/wiki/Smart_pointer http://en.wikipedia.org/wiki/Smart_pointer

"The copy constructor and assignment operators of std::auto_ptr do not actually copy the stored pointer. Instead, they transfer it, leaving the previous std::auto_ptr object empty. This was one way to implement strict ownership, so that only one auto_ptr object could own the pointer at any given time. This means that auto_ptr should not be used where copy semantics are needed." “ std :: auto_ptr的复制构造函数和赋值运算符实际上并不复制存储的指针。相反,它们将其转移,而将先前的std :: auto_ptr对象留空。这是实现严格所有权的一种方法,因此只有一个auto_ptr对象可以在任何给定时间拥有指针。这意味着在需要复制语义的地方不应该使用auto_ptr。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM