focus000/cppprimer

the behavior of default initialization of class members.

Opened this issue · 0 comments

C++ Primer 5th book tells us that default initialization happens

When we define nonstatic variables or arrays at block scope without initializers

in section 7.5.3. We also know that

variables of built-in type defined inside a function are uninitialized.

at page 44.

Is that mean it will be uninitialized if we define a int type class member without an initializer and then default initialize the class?

Then I decide test it, and the result makes me confused, here is my test code:

#include <iostream>
#include <vector>
#include <type_traits>

struct tests1
{
    int i;
    // std::vector<int> vi;
};

struct tests2
{
    int i;
    int j = 1;
    // std::vector<int> vi;
};

struct tests3
{
    int i;

private:
    int j;
};

class testc1
{
public:
    int i;
};

class testc2
{
public:
    int i;

private:
    int j;
};

int main()
{
    tests1 ts1;
    tests2 ts2;
    tests3 ts3;
    testc1 tc1;
    testc2 tc2;
    std::cout << ts1.i << " "
              << ts2.i << " "
              << ts3.i << " "
              << tc1.i << " "
              << tc2.i << " ";
    std::cout << std::endl;

    std::cout << std::boolalpha;
    std::cout << std::is_pod<tests1>::value << " "
              << std::is_pod<tests2>::value << " "
              << std::is_pod<tests3>::value << " "
              << std::is_pod<testc1>::value << " "
              << std::is_pod<testc2>::value << " ";
    std::cout << std::endl;

    std::cout << std::boolalpha;
    std::cout << std::is_trivial<tests1>::value << " "
              << std::is_trivial<tests2>::value << " "
              << std::is_trivial<tests3>::value << " "
              << std::is_trivial<testc1>::value << " "
              << std::is_trivial<testc2>::value << " ";
    std::cout << std::endl;

    std::vector<tests1> vts1(10);
    std::vector<tests2> vts2(10);
    std::cout << vts1[1].i << " "
              << vts2[2].i << " ";
    std::cout << std::endl;
}

and the result is:

265097253 -522024600 0 0 0 
true false false true false 
true false true true true 
0 0 

Here is my test environment:

Apple clang version 11.0.0 (clang-1100.0.33.8)
Target: x86_64-apple-darwin19.0.0
Thread model: posix
c++ standard: c++17

as we can see i in tests1 and tests2 is uninitialized, while in others is initialized to zero, and I have tested if it related to POStype and Trivialtype, and it seems not.

How to explain the result?