简体   繁体   中英

a compiler generated default constructor in c++

declaring a struct Table:

struct Tables {
       int i;
       int vi[10];
       Table t1;
       Table vt[10];
};

Tables tt;

assuming that a user-deault contructor is defined for Table.

here tt.t1 will be initialized using the default contructor for Table, as well as each element in tt.vt.

On the other hand tt.i and tt.vi are not initialized because those objects are not of a class type.

so we remain with a semi-initialized object tt.

if I understood well - if tt.i or tt.vi won't be explicitly initialized i the code, after creating tt, an error will be thrown if we try to read a value from them?

2) can someone explain it to me, why cpp designers didn't want to simply initialize the built-in types int and int[] to zero?

No, no error will be thrown. You will have a mild case of undefined behaviour. However, as integers don't have trap values, there is no way the behaviour can be detected.

Note that the C++ language itself throws exceptions only very, very rarely - about the only times I can think of where it does it is when performing an invalid cast to a reference via dynamic_cast , and when new fails to allocate. Of course the Standard Library may throw in a number of error conditions.

As to why C++ works that way (and C too), well initialisation takes time, and if it is not needed that is time wasted. For example, if you were going to read user input immediately into those variables, there is little point in initialising them before you do so.

An error won't be thrown, this isn't Java. :)

What will be returned will be whatever happens to be in the memory at that time. What you have is an "uninitialized" variable. It might be 0. It might be 42. It will be something unpredictable every time.

Moral of the story - initialize ALL of your variables. Failure to do so can cause incredibly difficult bugs down the road.

Since this is C++, use a default constructor to initialize your struct:

struct Tables { 
       int i; 
       int vi[10]; 
       Table t1; 
       Table vt[10]; 

Tables() {
  i = 0;
  for (int iter = 0; iter < 10; iter++)
    vi[iter] = 0;
}

}; 

Tables tt;

Since they are not pointer types, they will be populated with whatever is on the stack at that location. If they were pointer types and you dereferenced them without properly initializing them, then yes you would have issues.

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