三元运算符:编译器不发出局部变量警告的返回引用

Ternary operator: Compiler does not emit return reference of local variable warning

本文关键字:局部变量 警告 引用 返回 编译器 三元 运算符      更新时间:2023-10-16

我在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;
}

至于您问题中的实际代码:不会创建临时对象,因为您的maxoperator+都接受它们的参数并通过引用返回其结果。因此,代码实际上是有效的(如果奇怪/误导(。

但是,如果我们将您的代码简化为实际包含错误的版本:

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++ 中的一个错误/疏忽。

编译器实际上并不需要警告错误代码,但不幸的是,一个相当明显的损坏代码实例没有被诊断出来。