Left Up Right C++

Parameterübergabe: copyconstruktor oder Zuweisungsoperator ?

#include<iostream>

class Q
{
  int *i_;
public:
  Q() { std::clog << "Q()" << std::endl; i_=0; }
  Q(int i) { std::clog << "Q(" << i << ")" << std::endl; i_=new int(i); }
#ifdef ASSIGNMENT
  void operator=(const Q& qi)
  {
    std::clog << "operator=" << std::endl;
    if(*i_) delete i_;
    i_ = new int(*(qi.i_));
  }
#endif
#ifdef COPYKONSTRUCTOR
  Q(const Q& qo)
  {
    std::clog << "Q(const Q&)" << std::endl;
    i_ = new int(*(qo.i_));  
  }
#endif
  void p() { std::clog << "Inhalt ist " << *i_ << std::endl; }
  ~Q()
   {
     std::clog << "~Q()" << std::endl;
     delete i_;
   }  
};

void f(Q p)
{
  std::clog << "p.i=";
  p.p();
}

int main()
{
  Q qi(5);
  std::clog << "Funktionsaufruf Call by Value" << std::endl;
  f(qi);
  std::clog << "Zuweisung: " << std::endl;
  Q qi2(0);
  qi2=qi;
}

Compilierung

g++ -o cka -g -DASSIGNMENT -DCOPYKONSTRUCTOR ck.cpp
g++ -o ckc -g -DCOPYKONSTRUCTOR ck.cpp
g++ -o ckz -g -DASSIGNMENT  ck.cpp

Ergebnis:

Bei der Zuweisung:

Übrigens führt ckc zu einem Laufzeitfehler, weil der Zeiger einfach kopiert wird und im Destruktor 2 mal freigegeben wird.

Tip C++11

Man kann einen Konstruktor oder einen Operator explizit löschen:

Q(const Q& other)=delete;
Q& Q::operator=(const Q& other)=delete;

Dann meldet der Compiler eine Fehlermeldung, wenn er aufgerufen werden soll.

Bemerkungen aus dem Stroustrup-Buch

Der Copykonstruktor dient zur Initialisierung. und geht von einem uninizialisierem Zielobjekt aus

Der Zuweisungsoperator muß

Weiterer Links zum Copy-Construktor

https://www.geeksforgeeks.org/copy-constructor-in-cpp/

Informatik- und Netzwerkverein Ravensburg e.V Rudolf Weber