Why const for implicit conversion?

不问归期 提交于 2019-11-28 23:32:28

It doesn't really have much to do with the conversion being implicit. Moreover, it doesn't really have much to do with conversions. It is really about rvalues vs. lvalues.

When you convert 99 to type X, the result is an rvalue. In C++ results of conversions are always rvalues (unless you convert to reference type). It is illegal in C++ to attach non-const references to rvalues.

For example, this code will not compile

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

because it attempts to attach a non-const reference to an rvalue. On the other hand, this code is fine

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

because it is perfectly OK to attach a const reference to an rvalue.

The same thing happens in your code as well. The fact that it involves an implicit conversion is kinda beside the point. You can replace implicit conversion with an explicit one

implicit_conversion_func(X(99));

and end up with the same situation: with const it compiles, without const it doesn't.

Again, the only role the conversion (explicit or implicit) plays here is that it helps us to produce an rvalue. In general, you can produce an rvalue in some other way and run into the same issue

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

Per section 5.2.2 paragraph 5, when an argument to a function is of const reference type, a temporary variable is automatically introduced if needed. In your example, the rvalue result of X(99) has to be put into a temporary variable so that that variable can be passed by const reference to implicit_conversion_func.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!