[Bug c++/84656] -Wclass-memaccess spuriously warns in code paths that cannot access nontrivial types

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Thu Mar 1 21:50:00 GMT 2018


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

Martin Sebor <msebor at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
           Keywords|                            |diagnostic
             Status|UNCONFIRMED                 |RESOLVED
                 CC|                            |msebor at gcc dot gnu.org
         Resolution|---                         |WONTFIX

--- Comment #1 from Martin Sebor <msebor at gcc dot gnu.org> ---
The warning is implemented in the C++ front end and runs without the benefit of
any sort of constant propagation or dead code elimination, so there is no way
to avoid it in ordinary conditional statements.

In C++ 17 and later the warning can be avoided by using the if constexpr
statement:

  if constexpr (std::is_trivial<T>::value)
    memset(val, 0, sizeof(T);
  else
    *val = T();

In older C++ versions it can be avoided by dispatching to different
implementation functions at compile time.

In any event, the preferred way to zero-initialize an object is by making use
the appropriate initialization form.   It's safer and easier for compilers to
analyze both to detect bugs and to emit efficient code (sometimes more
efficient than memset), so I would recommend adopting it in favor or raw memory
functions even for trivial types.


More information about the Gcc-bugs mailing list