Search code examples
c++referenceconstantstemporary

Doubt on a C++ interview question


I have read Answers to C++ interview questions among which there is one that puzzles me:

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

My question is once the function argument is a const reference, why does the compiler generate the temporary variable, isn't that self-contradictory? Also, should the function Cube fail to compile because it modifies the const argument?


Solution

  • You are allowed to pass the results of an expression (including that of implicit casting) to a reference-to-const. The rationale is that while (const X & value) may be cheaper to use, depending on the copy-cost of type type X, than (X value), the effect is pretty much the same; value gets used but not modified (barring some dicey const-casting). Hence it is harmless to allow a temporary object to be created and passed to the function.

    You are not allowed to do so with pointer-to-const or reference-to-non-const, because unexpected (and bad) things can happen, such as you might expect the long temp to be cast back to long, which isn't going to happen.

    You're correct about num = num * num * num; being invalid. That's a bug in the text, but the argument made by it holds.