Delegating a constructor problem - is it safe?

This code calls another ctor in one ctor:

#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; } 

Result:

 ctor2 ctor1 1 dtor 2 dtor 

It seems that the member variable f destroyed here twice, is this normal?

+5
source share
1 answer

Here

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

You are not using a delegating constructor. What you do is create a temporary instance of Foo in the constructor body (and destroy it immediately).

Proper constructor delegation syntax

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

All Articles