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

后端 未结 2 838
一向
一向 2020-12-20 15:25

While looking at the GCC\'s warning options, I came across -Waggregate-return.

-Waggregate-return
Warn if any functio

相关标签:
2条回答
  • 2020-12-20 16:00

    Aggregates are defined in the C and C++ standards. The C version says (C99 6.2.5 Types/20-21):

    A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

    [...]

    Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.

    The C++ version says (N3485 8.5.1 [dcl.init.aggr]/1):

    An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

    Your second example (with std::string) doesn't trigger the warning because std::string has a user-provided constructor; and has private data members.

    It is my suspicion that this warning exists because it is considered poor style to return an aggregate in C; passing an out pointer is preferred in that language instead. I don't think it applies to C++ as much. But I can't confirm this with any data.

    0 讨论(0)
  • 2020-12-20 16:08

    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.

    0 讨论(0)
提交回复
热议问题