c++ - is reference conversion 是标准转换

标签 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;

我不知道为什么?

最佳答案

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

Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is reference-related to “cv2 T2” if T1 is the same type as T2, or T1 is a base class of T2. “cv1 T1” is reference-compatible with “cv2 T2” if T1 is reference-related to T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2.

在您的例子中,std::exceptionstd::runtime_exception 的基类,使 ref 引用与 例如。由于 exref 都不是 constvolatile,因此它们具有相同的 cv 限定,并且 refex 引用兼容。

§8.5.3¶5:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

— If the reference is an lvalue reference and the initializer expression

  — is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” (...)

ref 是一个左值引用,初始化表达式 ex 是一个左值,我们已经确定 refex

§8.5.3¶5 中的最后一句话也是相关的

In [the case I quoted above] the reference is said to bind directly to the initializer expression.

关于c++ - is reference conversion 是标准转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42409152/

相关文章:

c++ - 永远不会计算为常量表达式的 lambda() 可以是 C++ 中的 `constexpr` 函数吗?

c++ - 关于在执行不合格调用时使用名称与使用命名空间的歧义

c++ - Pointer-to-Pointer 在 Pointer 不存在的情况下崩溃

c++ - visual c++ 项目中的#define _WIN32_DCOM a 是什么?

c++ - 我对在 C++ 中将指针作为参数传递有什么误解?

c++ - 匿名命名空间中模板化类的友元

java - 使用导向器跨 C++ 和 Java 的 SWIG 多态性中的内存泄漏

c++ - 为什么这段 C++ 代码会打印出不应该打印的变量?

c++ - 标准如何支持在基类 S 中调用纯虚函数?

c++ - 在 C 和 C++ 中返回 void 类型