Cplusplus-cpp-copy-constructor

提供:Dev Guides
移動先:案内検索

C ++コピーコンストラクター

*copy constructor* は、以前に作成された同じクラスのオブジェクトで初期化することによりオブジェクトを作成するコンストラクターです。 コピーコンストラクタはに使用されます-
  • 同じタイプの別のオブジェクトから1つのオブジェクトを初期化します。
  • オブジェクトをコピーして、引数として関数に渡します。
  • オブジェクトをコピーして、関数から返す。

コピーコンストラクターがクラスで定義されていない場合、コンパイラーはそれを定義します。クラスにポインター変数があり、いくつかの動的なメモリ割り当てがある場合、コピーコンストラクターが必要です。 コピーコンストラクタの最も一般的な形式はここに示されています-

classname (const classname &obj) {
  //body of constructor
}

ここで、 obj は、別のオブジェクトを初期化するために使用されているオブジェクトへの参照です。

#include <iostream>

using namespace std;

class Line {

   public:
      int getLength( void );
      Line( int len );            //simple constructor
      Line( const Line &obj); //copy constructor
      ~Line();                    //destructor

   private:
      int *ptr;
};

//Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;

  //allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr;//copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

//Main function for the program
int main() {
   Line line(10);

   display(line);

   return 0;
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!

私たちは同じ例を見てみましょうが、同じタイプの既存のオブジェクトを使用して別のオブジェクトを作成するために小さな変更を加えて-

#include <iostream>

using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len );            //simple constructor
      Line( const Line &obj); //copy constructor
      ~Line();                    //destructor

   private:
      int *ptr;
};

//Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;

  //allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr;//copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

//Main function for the program
int main() {

   Line line1(10);

   Line line2 = line1;//This also calls copy constructor

   display(line1);
   display(line2);

   return 0;
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!