gpt4 book ai didi

c++ - 为什么要使用 const 进行隐式转换?

转载 作者:IT老高 更新时间:2023-10-28 23:17:12 26 4
gpt4 key购买 nike

广泛阅读ISO/IEC 14882, Programming language – C++我仍然不确定为什么需要 const 隐式转换为具有单个参数构造函数的用户定义类型,如下所示

#include <iostream>

class X {
public:
X( int value ) {
printf("constructor initialized with %i",value);
}
}

void implicit_conversion_func( const X& value ) {
//produces "constructor initialized with 99"
}

int main (int argc, char * const argv[]) {
implicit_conversion_func(99);
}



从第 4 节第 3 行开始

An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t (8.5). Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (8.5). The effect of either implicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The result is an lvalue if T is an lvalue reference type (8.3.2), and an rvalue otherwise. The expression e is used as an lvalue if and only if the initialization uses it as an lvalue.

随后我在 8.5 第 6 行中找到了与用户定义类型相关的初始化程序部分

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

最后,我在 12.3 第 2 行结束了关于用户定义转换的说明

User-defined conversions are applied only where they are unambiguous (10.2, 12.3.2).

不用说,10.2 和 12.3.2 没有回答我的问题。

  1. 有人能解释一下 const 对隐式转换的影响吗?
  2. const 的使用是否使转换按照 12.3 第 2 行“明确”?
  3. const 是否会影响第 4 节中谈到的左值和右值?

最佳答案

这与转换是隐式并没有太大关系。此外,它与转换 并没有太大关系。这真的是关于 rvalueslvalues

当您将 99 转换为类型 X 时,结果是一个 rvalue。在 C++ 中,转换的结果始终是右值(除非您转换为引用类型)。在 C++ 中,将非常量引用附加到右值是非法的。

例如,这段代码不会编译

X& r = X(99); // ERROR

因为它试图将非常量引用附加到右值。另一方面,这段代码很好

const X& cr = X(99); // OK

因为将 const 引用附加到右值是完全可以的。

同样的事情也会发生在您的代码中。它涉及隐式转换的事实有点无关紧要。您可以用显式替换隐式转换一个

implicit_conversion_func(X(99));

并以相同的情况结束:使用 const 可以编译,没有 const 则不会。

同样,转换(显式或隐式)在这里扮演的唯一角色是它帮助我们生成右值。通常,您可以通过其他方式生成右值并遇到相同的问题

int &ir = 3 + 2; // ERROR
const int &cir = 3 + 2; // OK

关于c++ - 为什么要使用 const 进行隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3895647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com