参考转换是标准转换

时间:2017-02-23 07:08:11

标签: c++ language-lawyer

c ++标准说标准转换包括

 A standard conversion sequence is a sequence of standard conversions in the following order:
(1.1) — Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion,
and function-to-pointer conversion.
(1.2) — Zero or one conversion from the following set: integral promotions, floating point promotion, integral
conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to
member conversions, and boolean conversions.
(1.3) — Zero or one qualification conversion.

但它没有提到参考转换。 这在c ++中被广泛使用;像:

auto ex = std::runtime_exception();
std::exception& ref = ex; //reference conversion


//reference to Derived converion to reference to Base in
// operator = call in object slicing
class B{};
class D : public B
{};
B b = d;

我不知道为什么?

1 个答案:

答案 0 :(得分:1)

参见C ++ 11标准中的§8.5.3¶4:

  

给定类型“cv1 T1”和“cv2 T2”,如果T1与T2的类型相同,则“cv1 T1”与“cv2 T2”相关,或者T1是T2的基类。如果T1与T2有参考相关性,则“cv1 T1”与“cv2 T2”参考兼容,并且cv1与cv2具有相同的cv资格,或者更高的cv资格。

在您的情况下,std::exceptionstd::runtime_exception的基类,使ref引用与ex相关。由于exref都不是constvolatile,因此它们具有相同的cv资格,refex的参考兼容

§8.5.3¶5:

  

对类型“cv1 T1”的引用由类型为“cv2 T2”的表达式初始化,如下所示:

     

- 如果引用是左值引用和初始化表达式

     

- 是左值(但不是位字段),“cv1 T1”与“cv2 T2”引用兼容,(...)

ref是左值参考,初始化表达式ex是左值,我们已经确定refex的参考兼容。

同样相关的是§8.5.3¶5

中的最后一句
  

在[我上面引用的情况]中,引用被称为直接绑定到初始化表达式。