命名空间
变体
操作

直接初始化

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
 
 

从构造函数实参的显式集合初始化对象。

内容

[edit] 语法

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 起)

[edit] 解释

直接初始化在下列情况下执行

1) 使用非空带括号的表达式列表 或带花括号的初始化列表(自 C++11 起) 初始化。
2) 使用单个花括号包围的初始化器初始化非类类型的对象 (注意:对于类类型和带花括号的初始化列表的其他用法,见列表初始化(自 C++11 起)
3) 通过函数式转型或带括号的表达式列表初始化一个 prvalue 临时量(直到 C++17)prvalue 的结果对象(自 C++17 起)
4) 通过 static_cast 表达式初始化一个 prvalue 临时量(直到 C++17)prvalue 的结果对象(自 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 相同的prvalue 表达式(忽略 cv 限定),则使用初始化器表达式本身,而不是从中物化的临时量,来初始化目标对象。
    (在 C++17 之前,编译器可能在这种情况下省略从 prvalue 临时量的构造,但相应的构造函数仍然必须是可访问的:参见复制省略
(自 C++17 起)
  • 检查 T 的构造函数,并通过重载决议选择最佳匹配。然后调用构造函数来初始化对象。
  • 否则,如果目标类型是(可能带有 cv 限定的)聚合类,则按照聚合初始化中所述的方式进行初始化,但允许窄化转换,不允许指定初始化器,绑定到引用的临时量的生命周期不会延长,没有花括号省略,并且任何没有初始化器的元素都将值初始化
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 限定版本,并且正在初始化的对象的初始值是(可能转换后的)值。

[edit] 注意

直接初始化比复制初始化更宽松:复制初始化仅考虑非显式构造函数和非显式用户定义的转换函数,而直接初始化考虑所有构造函数和所有用户定义的转换函数。

如果在使用直接初始化语法 (1) (带圆括号)的变量声明和函数声明之间存在歧义,则编译器始终选择函数声明。 此消除歧义规则有时违反直觉,并被称为最令人困惑的解析

#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}, {});
}

[edit] 示例

#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

[edit] 参见