Diese code ruft eine andere Ctor in einem Ctor:Konstruktorproblem delegieren - Ist es sicher?
#include <iostream>
using namespace std;
class F {
public:
F() { cout << "ctor1\n"; }
F(int) { cout << "ctor2\n"; }
~F() { cout << "dtor\n"; }
};
class Foo {
F f;
public:
Foo() : f() { cout << "1\n"; }
Foo(int i) : f(i) { Foo(); cout << "2\n"; }
};
int main() {
Foo object(1);
return 0;
}
Das Ergebnis ist:
ctor2
ctor1
1
dtor
2
dtor
Es scheint, die Membervariable f
zweimal hier zerstört, ist es in Ordnung?
Zusätzlich zu Anton Antwort, ich sehe nicht, warum „ctor2“ gedruckt wird. Ich denke, das sollte ctor1 sein http://coliru.stacked-crooked.com/a/bc8d4be86a5ccebf – user2950911
@ user2950911 Sorry, ich verwechselte die Version des Codes. Code wurde korrigiert. – songyuanyao