简体   繁体   中英

Default initialization

#include <iostream>

using namespace std;
class Apple
{
    public:
       int i;
       string s = "HelloWorld";
       string s1;
       bool b;
};

int main(int argc, char *argv[]) {
    Apple a; //doesn't this trigger default initialization??
    cout << a.i << a.s << a.s1 << a.b;

}

If the object is a local variable, then the data members will be be default-initialised. But here is the output: 0HelloWorld0 . Isn't this value initialization??

Isn't this value initialization??

On my machine, your program outputs -1219700747HelloWorld244 , a clear indicator for default initialisation.

That you get 0HelloWorld0 isn't fully random and can have many reasons. For example, it has something to do with your os architecture. All new memory for each program is initially zeroed, and this is why in this simple example, everything is set to zero. Or the compiler initializes the struct statically for performance reasons.

To quote the standard at 12.6.2/8:

In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then

— if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;

— otherwise, if the entity is an anonymous union or a variant member (9.5), no initialization is performed;

— otherwise, the entity is default-initialized (8.5).

Here's a simple test that indicates no value initialization is being performed in your code.

#include <iostream>
#include <string>

using namespace std;
class Apple
{
    public:
       int i;
       string s = "HelloWorld";
       string s1;
       bool b;
};

int main() 
{
   {
     Apple a; 
     a.i = 42;
     a.b = true;
     cout << a.i << a.s << a.s1 << a.b;
   }
   {
     Apple a; 
     cout << a.i << a.s << a.s1 << a.b;
   }
   {
     Apple a{}; 
     cout << a.i << a.s << a.s1 << a.b;
   }
}

Output:

42HelloWorld142HelloWorld10HelloWorld0

As you can see, in the second case those members still contain values from the previous assignment. Note that I'm not saying this is guaranteed or standard defined behavior.

In the third case you are indicating that the object should be value-initialized by adding the braces.

If your compiler doesn't support C++11's uniform initialization syntax, you can change it to the following to achieve the same effect.

Apple a = Apple();

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