mercredi 6 mai 2015

intialization of structs/classes without constructors in stack vs heap

I would like to know the rule for zeroing-out structs (or classes) that have no default constructor in C++.

In particular, it seems that if stored in the stack (say, as a local variable) they are uninitialized, but if allocated on the heap, they are zero-initialized (tested with GCC 4.9.1). Is this guaranteed to be portable?

Example program:

#include <iostream>
#include <map>
using namespace std;

struct X {
    int i, j, k;
    void show() { cout << i << " " << j << " " << k << endl; }
};

int fib(int i) {
    return (i > 1) ? fib(i-1) + fib(i-2) : 1;
}

int main() {
    map<int, X> m;            
    fib(10);                  // fills the stack with cruft
    X x1;                     // local
    X &x2 = m[1];             // heap-allocated within map
    X *x3 = new X();          // explicitly heap-allocated
    x1.show();  // --> outputs whatever was on the heap in those positions
    x2.show();  // --> outputs 0 0 0 
    x3->show(); // --> outputs 0 0 0     
    return 0;
}


Edited: removed an "or should I just use a constructor" in the bolded part; because what made me ask is that I want to know if it is guaranteed behaviour or not - we can all agree that readable code is better of with explicit constructors.

Aucun commentaire:

Enregistrer un commentaire