同时查看 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/