c++ - 关于-Waggregate-return 的目的/行为的混淆?

标签 c++ gcc g++ warnings gcc-warning

同时查看 GCC's warning options ,我遇到了-Waggregate-return

-Waggregate-return
Warn if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.)


引发警告的小例子:

class foo{};
foo f(void){return foo{};}
int main(){}

$ g++ -std=c++0x -Waggregate-return -o main main.cpp
main.cpp: In function ‘foo f()’:
main.cpp:2:5: warning: function returns an aggregate [-Waggregate-return]


另一个不会引发警告的小例子:

#include <string>
std::string f(void){return "test";}
int main(){}

使用-Waggregate-return 有什么好处?
为什么会有人想要收到关于此的警告?
另外,std::string 不是一个类吗?- 为什么我没有警告第二个示例中的“返回聚合”?

最佳答案

根据@AlokSave 的评论,这里是后来对答案的编辑:

对于这个编译器标志,有两种可能的解释。由于有关它的文献很少,它的原始含义有些不清楚,但主要有两种可能的解释:

1) 警告用户返回聚合对象,让他意识到如果返回聚合对象(分配在堆栈上),堆栈可能溢出。

2) 显然,一些旧的 C 编译器不支持返回聚合(你必须返回一个指针)。

这两个哪个是最好的,我很难判断。但是,可以在以下链接中找到有关此标志的更多相关信息:

http://bytes.com/topic/c/answers/644271-aggregate-return-warnings

https://lists.gnu.org/archive/html/bug-gnulib/2012-09/msg00006.html

引用后一个链接:

In the GNU apps I'm familiar with (Emacs, coreutils, ...) we simply disable -Waggregate-return. It a completely anachronistic warning, since its motivation was to support backwards compatibility with C compilers that did not allow returning structures. Those compilers are long dead and are no longer of practical concern.

关于c++ - 关于-Waggregate-return 的目的/行为的混淆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016993/

相关文章:

c - GCC - 将 int 分配给 char 时不应该发出警告吗?

java - 使用 gcc 编译时未创建输出文件

c++ - gcc/g++ 与 icc

c++ - Werror 不会将所有警告都变成错误

c++ - linux/g++ 链接的多重定义

c++ - 具有不同访问权限的类 : read-only to the many, 可写入特权

c++ - C++ 中的 SQLite char* 转换

c++ - 我是否正确删除了指向对象的指针 vector ?

c++ - boost spirit 的性能下降

c++ - 结合使用 -fno-unwind-tables 和 -fno-exceptions