简体   繁体   中英

Behaviors of default initialization on struct fields

When code is written like that:

#include <iostream>

using namespace std;

struct ID {
    char *name;
    int age;
};

int main() {
    ID a;

    cout << (long)(a.name) << endl;
    cout << a.age << endl;
    // cout << (a.name == nullptr) << endl;

    return 0;
}

The result is:

0
0

However, when it's written like that:

#include <iostream>

using namespace std;

struct ID {
    char *name;
    int age;
};

int main() {
    ID a;

    cout << (long)(a.name) << endl;
    cout << a.age << endl;
    cout << (a.name == nullptr) << endl;

    return 0;
}

The result seem strange:

140735032148552
1545300144
0

How could these 2 versions vary greatly?

Because of undefined behavior . Defining a local variable will not initialize it, the contents of the structure will be indeterminate, and using it will lead to said UB.

I found the answer myself. Thank you! Pileborg, Daniel and pstanisz. Your answer and comments are of great help to me.

My confusion came from a paragraph in "C++ Primer". In case anybody else has the same confusion, I write my understanding here.

Original word:

Under the new standard, we can supply an in-class initializer for a data member. When we create objects, the in-class initializers will be used to initialize the data members. Members without an initializer are default initialized (§ 2.2.1, p. 43). Thus, when we define Sales_data objects, units_sold and revenue will be initialized to 0, and bookNo will be initialized to the empty string.

-- "C++ Primer 5th edition"

I had thought that fields in a struct follow the same default initialization rule as global variable (ie initialized to their zero values). But it actually follows the same rule as local variables in a funtion, which is:

  1. All primitive built-in types are not initialized, leaving them to be random value originally in memory.
  2. Class types are initialized using their default constructor. If there is not a default constructor, the struct containing the class type cannot be created (proper parameters required).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM