2
#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
}

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

4

2 回答 2

8

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

auto_ptr<T> a;
auto_ptr<T> b(new T());
a = b; 

... 或者 ...

auto_ptr<T> b(new T());
auto_ptr<T> a(b);

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

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

于 2010-01-10T12:09:34.770 回答
0

您不应该将您的课程投射到 autoptr。我肯定知道。我不确定它想要什么语法,但它应该类似于 p = new YourClass()。

于 2010-01-10T12:06:43.283 回答