简体   繁体   中英

Initializing member variables of a struct in c++

I have a struct with a few double values:

struct A {
  double a;
  double b;
}

if I create a new struct, eg A a , are all the members (eg aa ) initialized to zeroes automatically in C++?

Not by default (unless it's a variable of static storage - that is, a static or global variable).

There are a few ways to initialize a struct of this kind to "zeros":

A a = { 0.0, 0.0 };
A a = { };

A a = A();

or if you have a C++11 compatible compiler:

A a{0.0, 0.0};
A a{}

or add a constructor to the struct definition:

struct A {
  double a;
  double b;
  A() : a(0.0), b(0.0) {}
};

8.5. Initializers [dcl.init] / 11 .

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value. [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. end note ]

and (ordering reversed for readability):

8.5. Initializers [dcl.init] / 6 .

To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

otherwise, no initialization is performed. [emphasis mine]

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

They are default initialized . For builtin types like int or double , their value depends on where the struct is declared (as a rule of thumb (but just as that): Assume they are always garbage unless initialized ) .

In global scope or/and with static storage, they are all zeroes (incl. when the struct is a member of a struct which is at global scope).

At function-local scope, they are full of garbage.

Example:

#include <iostream>

struct Foo {
    int x;
    int y;
};

Foo foo;

int main () {
    Foo bar;

    std::cout << foo.x << ":" << foo.y << '\n';
    std::cout << bar.x << ":" << bar.y << '\n';
}

This on the first run gives me

0:0
-1077978680:12574708

On the second run, without recompilation, this gives me:

0:0
-1075556168:12574708

A POD-struct can be initialized all zeroes using eg memset or just ...

Foo foo = {0}; // C and C++03
Foo foo{0}; // C++11

No. In the general case, they have unspecified values.

If you don't like this behaviour, you can provide a constructor:

struct A {
  double a;
  double b;

  A(): a(0.0), b(0.0) {}
}

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