#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。