Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

c++ - Zero-Initialize array member in initialization list

I have a class with an array member that I would like to initialize to all zeros.

class X
{
private:
    int m_array[10];
};

For a local variable, there is a straightforward way to zero-initialize (see here):

int myArray[10] = {};

Also, the class member m_array clearly needs to be initialized, as default-initializing ints will just leave random garbage, as explained here.

However, I can see two ways of doing this for a member array:

With parentheses:

public:
    X()
    : m_array()
    {}

With braces:

public:
    X()
    : m_array{}
    {}

Are both correct? Is there any difference between the two in C++11?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Initialising any member with () performs value initialisation.

Initialising any class type with a default constructor with {} performs value initialisation.

Initialising any other aggregate type (including arrays) with {} performs list initialisation, and is equivalent to initialising each of the aggregate's members with {}.

Initialising any reference type with {} constructs a temporary object, which is initialised from {}, and binds the reference to that temporary.

Initialising any other type with {} performs value initialisation.

Therefore, for pretty much all types, initialisation from {} will give the same result as value initialisation. You cannot have arrays of references, so those cannot be an exception. You might be able to construct arrays of aggregate class types without a default constructor, but compilers are not in agreement on the exact rules. But to get back to your question, all these corner cases do not really matter for you: for your specific array element type, they have the exact same effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...