Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a member variable of built-in type inside a global object zero initialised?

Tags:

To use an uninitialized object of built-in type with automatic storage duration is undefined behaviour. Of course I recommend strongly always to initialize member variables of built-in type inside a class type. Despite that, I assume that a member of built-in type without an initializer is always initialized to zero, if the corresponding object of class type has static storage duration (i.e. global object). My assumption is, that the complete memory of an object of class type with static storage duration is zeroed out.

Example:

#include <iostream>
using namespace std;

class Foo {
public:
        int bar;
};

Foo a;

int main() {
        Foo b;
        cout << "a.bar " << a.bar << "\n";
        cout << "b.bar " << b.bar << "\n";
        return 0;
}

Compile:

$ g++ -o init init.cpp -Wall -pedantic # gcc 7.2.1
init.cpp: In function ‘int main()’:
init.cpp:14:31: warning: ‘b.Foo::bar’ may be used uninitialized in this function [-Wmaybe-uninitialized]
  cout << "b.bar " << b.bar << "\n";
                               ^~~~

GCC complains only about the member, of class type object with automatic-storage duration b.bar not a.bar. So I am right?

Please feel free to modify the title of this question.

Thank you

like image 956
Peter Avatar asked Dec 21 '17 17:12

Peter


1 Answers

As said in the comment, it is zero initialized, [basic.start.init]/3:

Variables with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) shall be zero-initialized ([dcl.init]) before any other initialization takes place.[...]

And zero initializing an object, zero initializes all its non-static data members and padding bits, [dlc.init]/6.2:

To zero-initialize an object or reference of type T means:[...]

  • if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;[...]

So, as you said the complete object memory is zeroed out (bits belonging to its value representation and its padding-bits).

like image 71
Oliv Avatar answered Sep 29 '22 03:09

Oliv