songyuanyao
songyuanyao

Reputation: 172934

Delegating constructor issue - Is it safe?

This code is calling 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;
}

The result is:

ctor2
ctor1
1
dtor
2
dtor

It seems the member variable f destroyed twice here, is it Okay?

Upvotes: 6

Views: 79

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

Here

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

You are not using delegating constructor. What you're doing is creating a temporary instance of Foo in the constructor body (and destroying it immediately).

The correct syntax for delegating constructor is

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

Upvotes: 9

Related Questions