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
388 views
in Technique[技术] by (71.8m points)

different types of initialization in C++

I'm learning C++, and am rather confused as to the different types of initialization.

You can do:

T a;

which, as far as I can tell, will sometimes initialize a and sometimes won't, depending on if T has a default constructor.

You can also do:

T a(); // or
T a(1, 2, 3... args);

; (in some cases):

T a = 1; // implicitly converted to T sometimes?

; if there is no constructor:

T a = {1, 2, 3, 4, 5, 6};

; and also:

T a = T(1, 2, 3);

.

If you want to allocate on the heap, there's

T a = new T(1, 2, 3);

Is there anything else?

I'd like to know if a) I've got all the types of initialization covered and b) when to use each type?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You made a few mistakes. I'll clear them up.

// Bog-standard declaration.
// Initialisation rules are a bit complex.
T a;


// WRONG - this declares a function.
T a();

// Bog-standard declaration, with constructor arguments.
// (*)
T a(1, 2, 3... args);

// Bog-standard declaration, with *one* constructor argument
// (and only if there's a matching, _non-explicit_ constructor).
// (**)
T a = 1;

// Uses aggregate initialisation, inherited from C.
// Not always possible; depends on layout of T.
T a = {1, 2, 3, 4, 5, 6};

// Invoking C++0x initializer-list constructor.
T a{1, 2, 3, 4, 5, 6};

// This is actually two things.
// First you create a [nameless] rvalue with three
// constructor arguments (*), then you copy-construct
// a [named] T from it (**).
T a = T(1, 2, 3);

// Heap allocation, the result of which gets stored
// in a pointer.
T* a = new T(1, 2, 3);

// Heap allocation without constructor arguments.
T* a = new T;

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

...