简体   繁体   English

C++中的函数返回引用

[英]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.它不会编译,因为您不能将非常量引用绑定到临时引用(这是x*x的结果,临时intdouble&的返回类型甚至不兼容),即使您对此进行了纠正,您正在返回一个不正确的局部变量的引用,因为该变量在函数返回时超出了范围。

  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 x*x的类型是int ,所以返回一个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. x*x的结果可能太大而无法放入int ,在这种情况下,您可能希望使用更大的类型进行计算和返回值。 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).一种可能“更好”的方法是使用模板和通用转发引用(C++11 或更新版本)。

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

T could be double , int8_t , int , MyComplexMath::Quaternion ... anything that supports operator* . T 可以是doubleint8_tintint8_t MyComplexMath::Quaternion ...任何支持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.它仍然没有解决溢出问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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