2015-07-01 13 views
5

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?

+0

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

+0

@ user2950911 Sorry, ich verwechselte die Version des Codes. Code wurde korrigiert. – songyuanyao

Antwort

8

Hier

Foo(int i) { Foo(); cout << "2\n"; } 

Sie verwenden nicht delegieren Konstruktor. Was Sie tun, ist eine temporäre Instanz von Foo im Konstruktor Körper zu erstellen (und es sofort zu zerstören).

Die korrekte Syntax für Konstruktor Delegieren ist

Foo(int i) : Foo() { cout << "2\n"; } 
+0

Ich habe es. Vielen Dank! – songyuanyao

Verwandte Themen