简体   繁体   中英

C++: struct initialization in presence of constructor

I have question on C++ behavior when initializing structures using a list. For example, the following code behaves the same in C and C++. The list initializes x :

struct X {
    int x;
};

int main(int argc, char *argv[])
{
    struct X xx = {0};    
    return 0;
}

Now, if I add a constructor, I find out through testing that the constructor is called instead of the simple initialization of the x member:

#include <iostream>
using namespace std;

struct X {
    int x;
    X(int);
};

X::X(int i)
{
    cout << "X(int i)" << endl;
    x = i;
}

int main(int argc, char *argv[])
{
    struct X xx = {0};

    return 0;
}

Output:

X(int i)

Is the behavior of C++ with an identical constructor (as above) to override the simple list initialization? Giving my testing that is what appears to happen.

Thanks!

The following syntax:

X xx = {0};

is just a form of copy-list initialization . This has the effect of invoking the constructor of X , as you observed.

The name of this initialization comes from the fact that this looks like a list is being copied, but just the regular constructor is invoked. Note that this will only consider implicit constructors.

Also the elaborated-type-specifier struct is not necessary in c++, in the declaration of xx .

Note that if you don't provide a constructor such as X(int) (as you did in the first example), then the declaration of xx will instead do aggregate initialization.

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