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
开发者_StackOverflow中文版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?
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;
T a = 1; // implicitly converted to T sometimes?
You can do that if T has a copy constructor.
T a();
this sound more like a function declaration of "a" that return a type T
精彩评论