C++中不同类型的初始化

Aar*_*ken 15 c++

我正在学习C++,而且对于不同类型的初始化我感到很困惑.

你可以做:

T a;
Run Code Online (Sandbox Code Playgroud)

据我所知,有时会初始化a,有时也不会,具体取决于是否T有默认构造函数.

你也可以这样做:

T a(); // or
T a(1, 2, 3... args);
Run Code Online (Sandbox Code Playgroud)

; (在某些情况下):

T a = 1; // implicitly converted to T sometimes?
Run Code Online (Sandbox Code Playgroud)

; 如果没有构造函数:

T a = {1, 2, 3, 4, 5, 6};
Run Code Online (Sandbox Code Playgroud)

; 并且:

T a = T(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

.

如果你想在堆上分配,那就是

T a = new T(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

还有别的事吗?

我想知道a)我是否已经涵盖了所有类型的初始化,以及b)何时使用每种类型?

Lig*_*ica 15

你犯了一些错误.我会清理它们.

// 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;
Run Code Online (Sandbox Code Playgroud)