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

问题描述 投票:0回答:1

我在C ++中实现了一个简单的函数,它比较了两个对象,并返回了它们的max对象的引用,增加了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;
}
c++ reference compiler-warnings ternary-operator
1个回答
3
投票

至于你问题中的实际代码:没有创建临时对象,因为你的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 ++中的错误/疏忽。

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

© www.soinside.com 2019 - 2024. All rights reserved.