什么时候应该使用直接初始化和复制初始化? [英] When should you use direct initialization and when copy initialization?
本文介绍了什么时候应该使用直接初始化和复制初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
它只是偏好还是有特定的情况下,一个是必要的?我参考以下变量进行初始化
Is it simply preference or are there specific instances where one is necessary over another? I'm refering to the following variants for initialization
T t(e); // direct initialization
T t = e; // copy initialization
推荐答案
describe不是隐式和显式赋值,但是:
The actual names of the things you describe is not implicit and explicit assignment but :
- 复制初始化:
T x = a;
- 直接初始化:
T x(a);
- Copy-initialization :
T x = a;
- Direct-initialization :
T x(a);
它们是不等效的,特别是在需要转换的上下文中,例如 T
类类型和 a
是一个不同的类型(参见Alf注释的上下文,甚至不涉及转换的例子)。考虑下面的代码:
They are not equivalent, most notably in contexts where a conversion is required, for example when T
is of class type and a
is of a different type (see Alf comment for examples of contexts which don't even involve conversion). Consider the following code :
class Test
{
public:
explicit Test(int i) { /* ... */ }
};
int main()
{
Test t(0); // OK : calls Test::Test(int)
Test u = 0; // KO : constructor is marked explicit
}
):
- 对于直接初始化和复制初始化,其中源类型与类的相同或类的派生类目标,构造函数
- 对于其他复制初始化情况,如
main
我的示例,考虑用户定义的转换顺序。由于显式
关键字不允许使用Test
构造函数进行隐式转换,因此第二行无法编译。
- For direct-initialization and copy-initialization where the source type is the same as, or a derived class of, the class of destination, constructors are considered
- For other copy-initialization cases, like the second line of
main
in my example, user-defined conversion sequence are considered. As the use of theTest
constructor for implicit conversion was disallowed by theexplicit
keyword, the second line fails to compile.
这篇关于什么时候应该使用直接初始化和复制初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文