# Antworten

#### Content

Hier sind die Antworten zu den einzelnen Fragen:

• Das erste Beispiel:

#include <iostream>

class X {
private:
const char* name;
public:
X(const char* name) : name(name) {
std::cout << "X \"" << name << "\" constructed" << std::endl;
}
~X() {
std::cout << "X \"" << name << "\" destructed" << std::endl;
}
};

class Y {
public:
Y(const char* name) : x("within Y"), name(name) {
std::cout << "Y \"" << name << "\" constructed" << std::endl;
}
~Y() {
std::cout << "Y \"" << name << "\" destructed" << std::endl;
}
private:
X x;
const char* name;
};

X x = "global x";

int main() {
X x1 = "local x1";
Y* yp = new Y{"*yp (on heap)"};
X x2 = "local x2";
delete yp;
}

theon$g++ -Wall -o case05 case05.cpp theon$ ./case05
X "global x" constructed
X "local x1" constructed
X "within Y" constructed
Y "*yp (on heap)" constructed
X "local x2" constructed
Y "*yp (on heap)" destructed
X "within Y" destructed
X "local x2" destructed
X "local x1" destructed
X "global x" destructed
theon$ Da bei delete das Objekt sofort abgebaut wird, hängt die Reihenfolge der Abbauten nur vom Programmverlauf ab. • Hier ist eine Beispiellösung für die zweite Aufgabe: #include <iostream> class Chain { public: Chain(const char* name, Chain* next) : name(name), next(next) { std::cout << "Chain \"" << name << "\" constructed" << std::endl; } ~Chain() { delete next; std::cout << "Chain \"" << name << "\" destructed" << std::endl; } private: const char* name; Chain* next; }; int main() { Chain* c1p = new Chain("chain member #1", nullptr); Chain* c2p = new Chain("chain member #2", c1p); Chain* c3p = new Chain("chain member #3", c2p); delete c3p; }  theon$ g++ -Wall -o chain chain.cpp
theon$./chain Chain "chain member #1" constructed Chain "chain member #2" constructed Chain "chain member #3" constructed Chain "chain member #1" destructed Chain "chain member #2" destructed Chain "chain member #3" destructed theon$ 

Die Abbau-Meldungen kommen in umgekehrter Reihenfolge, wenn die beiden Anweisungen im destructor von Chain vertauscht werden:

theon$diff -U 2 chain.cpp chain-reversed.cpp --- chain.cpp 2018-05-03 10:44:25.000000000 +0200 +++ chain-reversed.cpp 2018-05-03 10:54:23.000000000 +0200 @@ -7,6 +7,6 @@ } ~Chain() { - delete next; std::cout << "Chain \"" << name << "\" destructed" << std::endl; + delete next; } private: theon$ g++ -Wall -o chain-reversed chain-reversed.cpp
theon$./chain-reversed Chain "chain member #1" constructed Chain "chain member #2" constructed Chain "chain member #3" constructed Chain "chain member #3" destructed Chain "chain member #2" destructed Chain "chain member #1" destructed theon$