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.
注意:这个问题在过去的试卷中,仅供修改。
2 个解决方案
#1
5
The code *autodp1
is effectively a dereferencing of a null pointer. Therefore the code exhibits undefined behavior.
代码* autodp1实际上是空指针的解引用。因此代码表现出不确定的行为。
You first construct autodp1
to point to the newly allocated double
. But then the constructor of autodp2
takes the owned memory for itself and sets autodp1
to null.
首先构造autodp1以指向新分配的double。但是然后autodp2的构造函数为自己获取拥有的内存并将autodp1设置为null。
#2
1
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
"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。“
#1
5
The code *autodp1
is effectively a dereferencing of a null pointer. Therefore the code exhibits undefined behavior.
代码* autodp1实际上是空指针的解引用。因此代码表现出不确定的行为。
You first construct autodp1
to point to the newly allocated double
. But then the constructor of autodp2
takes the owned memory for itself and sets autodp1
to null.
首先构造autodp1以指向新分配的double。但是然后autodp2的构造函数为自己获取拥有的内存并将autodp1设置为null。
#2
1
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
"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。“