Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++ - Confusion in regards to purpose/behavior of -Waggregate-return?

While looking at the GCC's warning options, I came across -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.)


small example that elicits the 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]


another small example that does not elicit the warning:

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

What is the benefit gained from using -Waggregate-return?
Why would someone want to be warned about this?
Also, isn't std::string a class?- why arn't I warned about the 'returned aggregate' in the second example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Following the comments made by @AlokSave, here is a later edit of the answer:

Three are two possible explanations for this compiler flag. Since the documentation about it is scarce, it is somewhat unclear what its original meaning is, but there are, mainly, two possible explanations:

1) Warning the user about returning an aggregate object make him aware that the stack could overflow if the aggregate object (which is allocated on the stack) is returned.

2) Apparently, some old C compiler did not support returning aggrregates (you had to return a pointer).

Which of the two is the best one, it is hard for me to judge. However, more relevant information about this flag may be found at the following links:

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

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

Quoting from the latter link:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...