c++ - 一道C++面试题的疑惑

标签 c++ reference constants temporary

我已阅读 Answers to C++ interview questions其中有一个让我很疑惑:

Q: When are temporary variables created by C++ compiler?

A: Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways.

a) The actual argument is the correct type, but it isn't Lvalue

double Cube(const double & num)
{
  num = num * num * num;
  return num;
}

double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue

b) The actual argument is of the wrong type, but of a type that can be converted to the correct type

 long temp = 3L;
 double value = cuberoot(temp); // long to double conversion

我的问题是一旦函数参数是一个const 引用,为什么编译器会生成临时变量,这不是自相矛盾吗?另外,函数 Cube 是否应该因为修改了 const 参数而无法编译?

最佳答案

我看不出有什么自相矛盾的地方。如果参数不是左值,或者类型错误,则由于显而易见的原因,不能将引用直接附加到参数;因此需要正确类型的中间临时文件。引用附加到该临时文件。

Cube 函数确实被破坏了(格式错误),因为它试图修改一个 const 值。

关于c++ - 一道C++面试题的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857728/

相关文章:

c - 如何确保传递给函数的指针及其内容不能仅在 c 中的函数 block 内修改

c++ - 如何检查文本文件是否以 UTF-8 编码?

c++ - 返回对字符串对象的引用,错误 : invalid initialization of reference of type âconst string&. c++

c - 将NULL分配给C中链表中的头节点

ms-access - 如何在 Access 中引用控件的属性

string - 尝试声明一个 String const 结果为预期类型,发现 "my string"

c++ - 如何获取游戏 Controller 名称(Windows 10/C++)

c++ - 使用 unique_ptr 时引用已删除的函数

c++ - 什么时候在窗口上设置最顶层不起作用?

函数体内部与外部的 C++ 常量和聚合