direct initialization
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
组明确的构造函数的参数初始化一个对象.
原文:
Initializes an object from explicit set of constructor arguments.
目录 |
[编辑] 语法
T object ( arg );
T object |
(1) | ||||||||
T object { arg };
T object |
(2) | (C++11 起) | |||||||
T ( other )
T |
(3) | ||||||||
static_cast< T >( other )
|
(4) | ||||||||
new T( args, ...)
|
(5) | ||||||||
Class:: Class() : member( args, ...) {...
|
(6) | ||||||||
[ arg](){...
|
(7) | (C++11 起) | |||||||
[编辑] 解释
在下列情况下进行直接初始化
原文:
Direct initialization is performed in the following situations:
1)
初始化一个非空的括号表达式列表
原文:
initialization with a nonempty parenthesized list of expressions
2)
3)
4)
一个prvalue临时一个的static_castexpession的初始化
原文:
initialization of a prvalue temporary by a 的static_cast expession
5)
初始化一个对象的动态存储一个非空的初始化一个新的表达与持续时间
原文:
initialization of an object with dynamic storage duration by a new-expression with a non-empty initializer
7)
关闭对象的成员初始化的变量副本在一个lambda表达式捕获
原文:
initialization of closure object members from the variables caught by copy in a lambda-expression
初始化直接的影响是:1
原文:
The effects of direct initialization are:
-
T
如果是一个类类型,构造函数的T
进行检查,并选择最佳匹配的重载决议。然后调用该构造函数初始化对象.原文:IfT
is a class type, the constructors ofT
are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.
[编辑] 注释
直接初始化是更宽松的复制初始化:复制初始化只考虑非显式构造函数和用户定义的转换函数,而直接初始化认为所有构造函数和隐式转换序列.
原文:
Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and user-defined conversion functions, while direct-initialization considers all constructors and implicit conversion sequences.
[编辑] 示例
#include <string> #include <iostream> #include <memory> 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