这是演员还是建筑? [英] Is this a cast or a construction?

查看:55
本文介绍了这是演员还是建筑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读完教科书上的内容后,我有些困惑。关于代码:

I'm a little confused after reading something in a textbook. Regarding the code:

void doSomeWork(const Widget& w)
{
    //Fun stuff.
}

doSomeWork(Widget(15));

doSomeWork()需要 const Widget& 参数。教科书《 Effective C ++ III》指出,这将创建一个临时的Widget对象,以传递给doSomeWork。它说可以替换为:

doSomeWork() takes a const Widget& parameter. The textbook, Effective C++ III, states that this creates a temporary Widget object to pass to doSomeWork. It says that this can be replaced by:

doSomeWork(static_cast<Widget>(15));

因为两个版本都是强制类型转换-第一个显然是函数式C强制类型转换。我本以为 Widget(15)会为带有一个整数参数的小部件调用一个构造函数。

as both versions are casts - the first is just a function-style C cast apparently. I would have thought that Widget(15) would invoke a constructor for widget taking one integer parameter though.

应该

推荐答案

在C ++中,这种表达式的一种形式至少在语法上即您使用C ++功能转换语法 Widget(15)创建类型为 Widget 的临时对象。

In C++ this kind of expression is a form of a cast, at least syntactically. I.e. you use a C++ functional cast syntax Widget(15) to create a temporary object of type Widget.

即使您使用多参数构造函数构造临时结构(如 Widget(1、2、3)),也是如此仍然被认为是功能演员表示法的一种变体(请参阅5.2.3)

Even when you construct a temporary using a multi-argument constructor (as in Widget(1, 2, 3)) it is still considered a variation of functional cast notation (see 5.2.3)

换句话说,您的这是演员还是建筑这个问题被错误地陈述,因为它暗示了演员和建筑之间的相互排他性。它们不是互斥的。实际上,每次类型转换(无论是显式强制转换还是更隐式的转换)都不过是目标类型的新临时对象(不包括某些引用初始化)的创建(构造)。

In other words, your "Is this a cast or a construction" question is incorrectly stated, since it implies mutual exclusivity between casts and "constructions". They are not mutually exclusive. In fact, every type conversion (be that an explicit cast or something more implicit) is nothing else than a creation ("construction") of a new temporary object of the target type (excluding, maybe, some reference initializations).

BTW,功能强制转换表示法主要是C ++表示法。 C语言没有函数式强制转换。

BTW, functional cast notation is a chiefly C++ notation. C language has no functional-style casts.

这篇关于这是演员还是建筑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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