混淆与直接初始化和副本初始化 [英] Confused with direct initialization and copy initialization

查看:152
本文介绍了混淆与直接初始化和副本初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下概念感到困惑:

I am confused with followed concepts:

string str="123";

有些书说:=是复制初始化,

Some books say that: using "=" is copy initialization,

但是一些文章说: string str =123 string str(123)。毫无疑问,str(123)是直接初始化。

but some articles say: string str="123" is same as string str("123"). There is no doubt str("123") is directly initialization.

因此, string str =123;

如何判断哪个是复制初始化或直接初始化?

How to judge which is copy initialization or directly initialization?

推荐答案


  • T x = y;

T x(y); em> direct-initialization 。

T x(y); is direct-initialization.

。发生什么取决于 T 是什么类型。对于原始类型(例如 int s),两者是完全相同的。对于类类型(例如 std :: string ),这两个实际上是相同的,虽然copy-initialization要求一个拷贝构造函数是可访问的和非显式的但实际上不会被调用)。

This is true for any type T. What happens exactly depends on what sort of type T is. For primitive types (e.g. ints), the two are exactly the same. For class-types (such as std::string), the two are practically the same, though copy-initialization requires that a copy-constructor be accessible and non-explicit (though it will not actually be called in practice).

这篇关于混淆与直接初始化和副本初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆