我在 C++ 中实现了一个简单的函数,它比较两个对象并返回它们的最大对象的引用增加 1。我希望创建一个时间对象,并且当返回该对象的引用时,警告由于临时对象的悬垂引用,编译器将出现。但不会产生任何警告。我很难理解为什么会这样。
下面是我写的代码
#include <iostream>
#include <string>
class A
{
public:
A():v(0)
{
std::cout << "A::ctror" <<std::endl;
}
A (int const & x):v(v + x)
{
std::cout << "convertion::ctror(int)" << std::endl;
}
static A & max(A & x , A & y)
{
return x.v > y.v ? (x+1) : (y +1 ) ;
}
A & operator +( A const a )
{
this->v+=a.v;
return *this;
}
int v ;
};
int main()
{
A a1;
A a2;
a1.v = 1;
a2.v = 6;
A const & a3 = A::max(a1,a2);
std::cout << a3.v << std::endl;
}
最佳答案
至于您问题中的实际代码:没有创建临时对象,因为您的 max
和 operator+
都采用它们的参数并通过引用返回它们的结果。因此代码实际上是有效的(如果奇怪/误导)。
但是,如果我们将您的代码简化为实际包含错误的版本:
struct A
{
static int &foo(int &x)
{
int a = 42;
return x < a ? x : a;
}
};
int main()
{
int n = 0;
return A::foo(n);
}
...我们仍然没有收到警告,至少在 g++ 8.3.1 中没有。
这似乎与 foo
是成员函数和/或标记为 static
有关。没有类包装器:
static int &foo(int &x)
{
int a = 42;
return x < a ? x : a;
}
int main()
{
int n = 0;
return foo(n);
}
...仍然没有警告。
类似地,没有static
:
struct A
{
int &foo(int &x)
{
int a = 42;
return x < a ? x : a;
}
};
int main()
{
A wtf;
int n = 0;
return wtf.foo(n);
}
...也没有警告。
但是没有类和static
:
int &foo(int &x)
{
int a = 42;
return x < a ? x : a;
}
int main()
{
int n = 0;
return foo(n);
}
.code.tio.cpp: In function ‘int& foo(int&)’:
.code.tio.cpp:4:24: warning: function may return address of local variable [-Wreturn-local-addr]
return x < a ? x : a;
^
...正如预期的那样。
我怀疑这是 g++ 中的错误/疏忽。
编译器实际上并不需要针对错误代码发出警告,但遗憾的是未诊断出相当明显的错误代码实例。
关于c++ - 三元运算符 : Compiler does not emit return reference of local variable warning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55781379/