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::exception
是 std::runtime_exception
的基类,使 ref
引用与 例如
。由于 ex
和 ref
都不是 const
或 volatile
,因此它们具有相同的 cv 限定,并且 ref
与 ex
引用兼容。
§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
是一个左值,我们已经确定 ref
与 ex
。
§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/