Does writing a default constructor trigger zero initialization?

These are the definitions of my class:

class Foo{
    int _ent;
public:
    void printEnt() const{cout << _ent << ' ';}
};

class Bar{
    Foo _foo;
public:
    void printEnt() const{_foo.printEnt();}
};

And this is my test code:

char* buf = new char[sizeof(Foo) + sizeof(Foo) + sizeof(Bar)];

fill(buf, buf + sizeof(Foo) + sizeof(Foo) + sizeof(Bar), 'J');

cout << ((int*)buf)[0] << ' ' << ((int*)buf)[1] << ' ' << ((int*)buf)[2] << endl;

Foo* first = new (buf) Foo;
Foo* second = new (buf + sizeof(Foo)) Foo();
Bar* third = new (buf + sizeof(Foo) * 2) Bar;

first->printEnt(); second->printEnt(); third->printEnt();

My conclusion:

1246382666 1246382666 1246382666
1246382666 0 1246382666

But if I add publicthe default ctor to Foo:Foo() : _ent(0) {}

My conclusion will be:

1246382666 1246382666 1246382666
0 0 0

Is this the right behavior? Should adding my own default ctor remove the default initialization capability?

I run this code on gcc 4.8.1, if that matters. The results must be reliable, because I run debugging and state:assert(sizeof(Foo) == sizeof(int) && sizeof(Bar) == sizeof(int));

+1
source share
3

, , . . , Foo::Foo(), , a Foo; , , . , , .

EDIT:

§8.5/7, :

T :

- T (, cv-) ( 9), (12.1) T [...]

, , , , , §12.1/4; , .

§ 8.5/8. , , , .

, : ++ standard: , . -, . , , , ( , ).

+3

++ 11 :

class Foo{
    int _ent=0;
public:

    // ...
};

, - , .

+1

When you provide the default constructor, you no longer get the compiler generated. Since your constructor initializes the member to 0 by default, the member will always be 0, this is especially true since the member is private and you cannot change it.

0
source

Source: https://habr.com/ru/post/1567999/


All Articles