命名空间
变体
操作

直接初始化

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

使用一组显式构造函数参数初始化对象。

目录

[编辑] 语法

T 对象 ( arg );

T 对象 ( arg1, arg2, ... );

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

T ( arg1, arg2, ... )

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

[编辑] 解释

直接初始化在以下情况发生

1) 使用非空括号表达式列表 或花括号初始化列表(C++11 起) 进行初始化。
2) 使用单个花括号初始化器初始化非类类型对象 (注意:对于类类型和花括号初始化列表的其他用途,请参见列表初始化(C++11 起)
3) 通过函数式转型或带括号的表达式列表初始化纯右值临时对象(C++17 前)纯右值的结果对象(C++17 起)
4) 通过 static_cast 表达式初始化纯右值临时对象(C++17 前)纯右值的结果对象(C++17 起)
5) 通过带初始化器的 new-expression 初始化具有动态存储期的对象。
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-限定符)纯右值表达式,则使用初始化器表达式本身而不是从其具象化的临时对象来初始化目标对象。
    (在 C++17 之前,编译器可能在此情况下消除纯右值临时对象的构造,但相应的构造函数必须仍然可访问:参见拷贝消除
(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-非限定版本,并且正在初始化的对象的初始值是(可能已转换的)值。

[编辑] 注意

直接初始化比拷贝初始化更宽容:拷贝初始化只考虑非explicit构造函数和非 explicit 用户定义转换函数,而直接初始化考虑所有构造函数和所有用户定义转换函数。

在使用直接初始化语法 (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}, {});
}

[编辑] 示例

#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

[编辑] 另请参见