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 の値に問題はありません (2 回目に呼び出されたとき)。初期化されたときと同じままです)。それは変わらないままです。クラス MyClass からコピー コンストラクターを削除すると、(2 回目に呼び出されたときに) 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 メンバーをコピーするときに上記と同様のことを行います。したがって、コピー コンストラクターが呼び出された後、コピーされたfromクラスには NULL メンバーが含まれます。

于 2010-01-10T12:09:34.770 に答える
0

クラスをautoptrにキャストしないでください。私は確かにそれを知っています。頭のてっぺんからどのような構文が必要かはわかりませんが、p = new YourClass() のようなものにする必要があります。

于 2010-01-10T12:06:43.283 に答える