#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; }
g++ -o cka -g -DASSIGNMENT -DCOPYKONSTRUCTOR ck.cpp g++ -o ckc -g -DCOPYKONSTRUCTOR ck.cpp g++ -o ckz -g -DASSIGNMENT ck.cpp
Übrigens führt ckc zu einem Laufzeitfehler, weil der Zeiger einfach kopiert wird und im Destruktor 2 mal freigegeben wird.
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.
Der Zuweisungsoperator muß