命名空間
變體
動作

直接初始化

出自 cppreference.com
< cpp‎ | language
 
 
C++ 語言
一般主題
流程控制
條件執行陳述式
if
疊代陳述式 (迴圈)
for
範圍 for (C++11)
跳躍陳述式
函式
函式宣告
Lambda 函式運算式
inline 指定符
動態例外規範 (直到 C++17*)
noexcept 指定符 (C++11)
例外
命名空間
型別
指定符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
儲存期指定符
初始化
 
 

透過明確指定的建構函式參數集合來初始化物件。

目錄

[編輯] 語法

T object ( arg );

T object ( arg1, arg2, ... );

(1)
T object { arg }; (2) (C++11 起)
T ( other )

T ( arg1, arg2, ... )

(3)
static_cast< T >( other ) (4)
new T( args, ... ) (5)
Class::Class() : member( args, ... ) { ... } (6)
[arg]() { ... } (7) (C++11 起)

[編輯] 解釋

以下情況會進行直接初始化:

1) 使用非空的括號表示式列表 或大括號初始化列表 (braced-init-lists)(C++11 起) 進行初始化。
2) 以單個大括號包圍的初始化器對非類別型別的物件進行初始化 (註:對於類別型別及大括號初始化列表的其他用法,請參閱列表初始化(C++11 起)
3) 透過函數風格轉型 (function-style cast) 或帶有括號的表示式列表,對 純右值暫存物件 (prvalue temporary)(C++17 前)純右值的結果物件(C++17 起) 進行初始化。
4) 透過 static_cast 表示式,對 純右值暫存物件(C++17 前)純右值的結果物件(C++17 起) 進行初始化。
5) 透過帶有初始化器的 new 表示式,對具有動態儲存期的物件進行初始化。
6) 透過建構函式初始化列表,對基底類別或非靜態成員進行初始化。
7) 透過 lambda 表示式中以複製方式捕捉的變數,對閉包物件成員進行初始化。

直接初始化的效果如下:

  • T 為陣列型別,
  • 程式格式錯誤。
(直到 C++20)
struct A
{
    explicit A(int i = 0) {}
};
 
A a[2](A(1)); // OK: initializes a[0] with A(1) and a[1] with A()
A b[2]{A(1)}; // error: implicit copy-list-initialization of b[1]
              //        from {} selected explicit constructor
(自 C++20 起)
  • T 為類別型別,
  • 若初始化器是與 T 型別相同(忽略 cv 限定符)的純右值 (prvalue) 表示式,則直接使用該初始化器表示式本身來初始化目標物件,而非從中具現化出的暫存物件。
    (在 C++17 之前,編譯器在此情況下可能會省略從純右值暫存物件進行的建構,但仍須確保對應的建構函式可存取:請參閱複製省略 (copy elision))
(自 C++17 起)
  • 檢查 T 的建構函式,並透過多載決議選出最佳匹配。隨後呼叫該建構函式以初始化物件。
  • 否則,若目標型別為(可能帶有 cv 限定符的)聚合類別,則其初始化方式如聚合初始化所述,差別在於允許縮小轉換、不允許指定初始化器 (designated initializers)、綁定到參考的暫存物件其生命週期不會延長、不進行大括號省略,且任何未提供初始化器的元素皆會進行值初始化
struct B
{
    int a;
    int&& r;
};
 
int f();
int n = 10;
 
B b1{1, f()};            // OK, lifetime is extended
B b2(1, f());            // well-formed, but dangling reference
B b3{1.0, 1};            // error: narrowing conversion
B b4(1.0, 1);            // well-formed, but dangling reference
B b5(1.0, std::move(n)); // OK
(自 C++20 起)
  • 否則,若 T 為非類別型別但來源型別為類別型別,則會檢查來源型別及其基底類別(若有)的轉換函式,並透過多載決議選出最佳匹配。隨後使用該被選定的使用者定義轉換來將初始化器表示式轉換為正在被初始化的物件。
  • 否則,若 Tbool 且來源型別為 std::nullptr_t,則初始化後的物件值為 false
  • 否則,必要時使用標準轉換other 的值轉換為 T 的 cv 無限定版本,該物件的初始值即為該(可能經轉換後的)值。

[編輯] 註解

直接初始化比複製初始化更寬鬆:複製初始化僅考慮非 explicit 的建構函式及非 explicit 的使用者定義轉換函式,而直接初始化則考慮所有的建構函式及所有的使用者定義轉換函式。

當使用直接初始化語法 (1)(帶有圓括號)的變數宣告與函數宣告發生歧義時,編譯器總是會選擇函數宣告。這種消除歧義的規則有時與直覺不符,因此被稱為最煩人的解析 (most vexing parse)

#include <fstream>
#include <iterator>
#include <string>
 
int main()
{
    std::ifstream file("data.txt");
 
    // The following is a function declaration:
    std::string foo1(std::istreambuf_iterator<char>(file),
                     std::istreambuf_iterator<char>());
    // It declares a function called foo1, whose return type is std::string,
    // first parameter has type std::istreambuf_iterator<char> and the name "file",
    // second parameter has no name and has type std::istreambuf_iterator<char>(),
    // which is rewritten to function pointer type std::istreambuf_iterator<char>(*)()
 
    // Pre-C++11 fix (to declare a variable) - add extra parentheses around one
    // of the arguments:
    std::string str1((std::istreambuf_iterator<char>(file)),
                      std::istreambuf_iterator<char>());
 
    // Post-C++11 fix (to declare a variable) - use list-initialization for any
    // of the arguments:
    std::string str2(std::istreambuf_iterator<char>{file}, {});
}

[編輯] 範例

#include <iostream>
#include <memory>
#include <string>
 
struct Foo
{
    int mem;
    explicit Foo(int n) : mem(n) {}
};
 
int main()
{
    std::string s1("test"); // constructor from const char*
    std::string s2(10, 'a');
 
    std::unique_ptr<int> p(new int(1));  // OK: explicit constructors allowed
//  std::unique_ptr<int> p = new int(1); // error: constructor is explicit
 
    Foo f(2); // f is direct-initialized:
              // constructor parameter n is copy-initialized from the rvalue 2
              // f.mem is direct-initialized from the parameter n
//  Foo f2 = 2; // error: constructor is explicit
 
    std::cout << s1 << ' ' << s2 << ' ' << *p << ' ' << f.mem  << '\n';
}

輸出

test aaaaaaaaaa 1 2

[編輯] 參閱

English Deutsch 日本語 한국어 中文(简体) 中文(繁體)