This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug c++/81109] [8 Regression] new -Wclass-memaccess warning noisy


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81109

--- Comment #3 from Martin Sebor <msebor at gcc dot gnu.org> ---
Calling memset to clear an object with a non-trivial default ctor doesn't
zero-initialize the object (or begin its lifetime), or establish any invariants
that the default ctor would otherwise set up.  Using the object after the
memset call is undefined, and the warning correctly points that out.  Examples
where clearing such an object is wrong and dangerous is a class that defines
either a reference member, or a const data member, or a pointer to member
object.  The correct way to initialize or clear such objects is by calling the
provided constructor or the copy assignment operator, whichever is appropriate.

In the test case in comment #0, the default ctor for A is private so the only
viable alternative is to use the trivial copy assignment operator to copy an
existing object to cache_[0].  This is also the suggestion offered by the
warning.

If the effects of the default ctor are the same as those of memset(this, 0,
sizeof *this) the ctor can either be omitted (assuming no other ctors are
defined) or, in C++ 11, defaulted(*).  That will eliminate the warning as well
as the overhead of the call if the user-provided ctor is not defined inline. 
Otherwise, using the special function in a loop when the size of the object is
not constant (e.g., when clearing an array with a runtime bound) can be more
efficient than calling memset because GCC only inlines memset with constant
sizes.

Alternatively, if none of these solutions is workable, the warning can be
suppressed by storing the address of the object in a named void* temporary and
using it as an argument to memset:

  void Flush() { void *p = cache_; __builtin_memset(p, 0, sizeof cache_); }

[*] It might be a useful enhancement to add an option to detect such ctors and
have GCC suggest one of these alternatives.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]