Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 256
songyuanyao Avatar asked Jul 01 '15 08:07

songyuanyao


1 Answers

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"; }
like image 72
Anton Savin Avatar answered Oct 03 '22 08:10

Anton Savin