auto_ptr莫名其妙的行为

San*_*eep 2 c++ smart-pointers

#include<iostream>
#include<memory>
#include<stdio>

using namespace std;

class YourClass
{
   int y;
public:
   YourClass(int x) {
      y= x;
   }
};
class MyClass
{
   auto_ptr<YourClass> p;
public:
   MyClass() //:p(new YourClass(10)) 
   {
      p= (auto_ptr<YourClass>)new YourClass(10);
   }
   MyClass( const MyClass &) : p(new YourClass(10)) {}
   void show() {
      //cout<<'\n'<<p; //Was not working hence commented
      printf("%p\n",p);
   }
};

int main() {
   MyClass a;
   a.show();
   MyClass b=a;
   cout<<'\n'<<"After copying";
   a.show();//If I remove copy constructor from class this becomes NULL(the value of auto_ptr becomes NULL but if class has copy constructor it remains same(unchanged)
   b.show();//expected bahavior with copy construcotr and withought copy constructor
}
Run Code Online (Sandbox Code Playgroud)

使问题更具体:目前该类具有复制构造函数,因此a.show()打印的auto_ptr值没有问题(当它第二次被调用时).它与它刚化时的情况相同.它改变了.如果我从类MyClass中删除了复制构造函数,则a.show()打印的auto_ptr的值(当它被第二次调用时)为NULL.

max*_*ori 8

发生的事情是由于奇怪的(但只有你考虑它才合理)分配或复制auto_ptr的语义,例如

auto_ptr<T> a;
auto_ptr<T> b(new T());
a = b; 
Run Code Online (Sandbox Code Playgroud)

... 要么 ...

auto_ptr<T> b(new T());
auto_ptr<T> a(b);
Run Code Online (Sandbox Code Playgroud)

这些将按预期设置为b,但它们也将b设置为NULL(请参阅http://www.cplusplus.com/reference/std/memory/auto_ptr/auto_ptr/).

如果没有为MyClass定义复制构造函数,那么编译器将为您生成一个复制构造函数,并在复制auto_ptr成员时执行与上面类似的操作.因此,在调用复制构造函数之后,类复制将具有NULL成员.