这两个C ++初始化语法在语义上有什么不同吗? [英] Do these two C++ initializer syntaxes ever differ in semantics?

查看:95
本文介绍了这两个C ++初始化语法在语义上有什么不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设下面的代码是正确编译的合法代码, T 是类型名称, x 是变量的名称。



语法一:

  T a(x); 

语法二:

  T a = x; 

这两个表达式的确切语义是否不同?如果是,在什么情况下?



如果这两个表达式有不同的语义,我也很想知道标准的哪一部分谈论这个。 >

此外,如果有一个特殊情况,T是标量类型的名称(aka, int long double 等等),当T是标量类型与非标量类型?

解决方案

是的。如果x的类型不是 T ,则第二个示例扩展为 T a = T(x)。这要求 T(T const&)是公共的。第一个例子不调用拷贝构造函数。



在检查辅助功能后,可以删除拷贝(正如托尼指出的那样)。但是,在检查辅助功能之前无法消除


Assume that the following code is legal code that compiles properly, that T is a type name, and that x is the name of a variable.

Syntax one:

T a(x);

Syntax two:

T a = x;

Do the exact semantics of these two expressions ever differ? If so, under what circumstances?

If these two expressions ever do have different semantics I'm also really curious about which part of the standard talks about this.

Also, if there is a special case when T is the name of a scalar type (aka, int, long, double, etc...), what are the differences when T is a scalar type vs. a non-scalar type?

解决方案

Yes. If the type of x is not T, then the second example expands to T a = T(x). This requires that T(T const&) is public. The first example doesn't invoke the copy constructor.

After the accessibility has been checked, the copy can be eliminated (as Tony pointed out). However, it cannot be eliminated before checking accessibility.

这篇关于这两个C ++初始化语法在语义上有什么不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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