三元运算符:编译器不发出局部变量警告的返回引用
Ternary operator: Compiler does not emit return reference of local variable warning
我在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++ 中的一个错误/疏忽。
编译器实际上并不需要警告错误代码,但不幸的是,一个相当明显的损坏代码实例没有被诊断出来。
相关文章:
- 警告 C4101 未引用的局部变量
- libmysql:警告:返回局部变量"行"的地址(C++/C)
- 为什么 ++ 运算符触发器返回对局部变量警告的引用
- 三元运算符:编译器不发出局部变量警告的返回引用
- 为什么 C++ 编译器不警告返回对局部变量的引用
- 警告:返回局部变量'buffer'地址
- 没有返回对局部变量的引用的编译器警告
- 警告:返回局部变量"角度"的地址 [-Wreturn-local-addr]
- 警告 C4700:未初始化的局部变量
- 为什么编译器在返回对局部变量的局部引用时不警告"returning address of local variable or temporary"?
- 在 catch 块中使用 g++ 或 clang++ 启用未引用的局部变量警告
- 编译器警告 re:对局部变量的引用
- 将未初始化的局部变量传递给函数时,C++编译器警告(?)
- 警告 C4700:使用未初始化的局部变量"p"
- 纯虚函数=未引用的局部变量警告
- 非局部变量在c++中使用匿名类型警告
- 捕获带有未引用局部变量警告的异常
- 禁用局部变量的未初始化警告
- 如何在g++中设置警告,以警告返回指向局部变量的指针
- GCC 中的断言和未使用的局部变量警告不能很好地混合?