简体   繁体   中英

Function return reference in C++

double& squaredX (double x)
{
   return x*x;
}
  1. What would be the potential problem of this function?
  2. What is the best way to rewrite the function?
  1. What would be the potential problem of this function?

It doesn't compile, because you cannot bind a non-const reference to a temporary (which is the result of x*x , a temporary int , and the return type of double& is not even compatible) and even if you correct for that, you are returning a reference of a local variable which is incorrect, as the variable goes out of scope when the function returns.

  1. What is the best way to rewrite the function?

The type of x*x is int , so it makes sense to return an int

int squaredX (int x)
{
   return x*x;
}

It's possible that the result of x*x is too large to fit into an int , in which case you may want to use a larger type for the calculation and return value. But that depends on the particulars of the situation.

One way that could be "better" is to use templates and universal forwarding references (C++11 or newer).

 template<typename T>
 T square(const T&& x)
 {
     return x*x;
 }

T could be double , int8_t , int , MyComplexMath::Quaternion ... anything that supports operator* . It also supports pass by reference in case the argument is expensive to copy.

Arguably, this might (rightly so) scare away people, so may not "best". It still doesn't address overflows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM