mercredi 26 juin 2019

Why brace initialization assignment fills variable with garbage

I have fallen into belief that variables are assigned to it's default values when using a brace initialization. But I was wrong.

In the following example:

#include <string>
#include <iostream>

#include <stdint.h>


class A
{
public:
    A() {}
    ~A(){}

    int var1;
    int32_t var2;
    int64_t var3;
    std::string var4;
    double var5;
    float var6;

    std::string info() const {
        return "var1=" + std::to_string(var1) + " " +
               "var2=" + std::to_string(var2) + " " +
               "var3=" + std::to_string(var3) + " " +
               "var4=" + var4 + " " +
               "var5=" + std::to_string(var5) + " " +
               "var6=" + std::to_string(var6) + " " +
               "\n"
               ;
    }
};

int main()
{
    A a;
    std::cout << "Before assigning variables: " << a.info();

    a.var1 = 1;
    a.var2 = 2;
    a.var3 = 3;
    a.var4 = "4";
    a.var5 = 5;
    a.var6 = 6;
    std::cout << "After assigning variables: " << a.info();

    a = {};
    std::cout << "After brace init assignemnt: " << a.info();
}

Here is the result:

Before assigning variables: var1=0 var2=0 var3=4198240 var4= var5=0.000000 var6=0.000000 
After assigning variables: var1=1 var2=2 var3=3 var4=4 var5=5.000000 var6=6.000000 
After brace init assignemnt: var1=2114725200 var2=32766 var3=4199416 var4= var5=0.000000 var6=0.000000

To fix this I need ethier to get rid of default constructor, or assign each variable with brace constructor: int var1{};

Can someone please explain why this happens?

Aucun commentaire:

Enregistrer un commentaire