[Bug c++/85707] -Wclass-memaccess should excempt safe usage inside of a class and its friends

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed May 9 18:08:00 GMT 2018


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

--- Comment #9 from Martin Sebor <msebor at gcc dot gnu.org> ---
The purpose of friendship is to grant access to class members that would
otherwise be inaccessible.  The purpose of constructors is to establish class
invariants, and it is the responsibility of member functions and friends to
maintain them.  There can certainly be implementation-only functions that need
to temporarily break invariants and HashTable::init_table_memset() could be
viewed as one, but those are the exceptions to the rule.

The goal of the warning is to help detect likely coding mistakes.  In some
cases, it's impossible to reliably distinguish these from carefully crafted
code that is actually safe.  It's a judgment call whether to err on the side of
false positives or false negatives.  I think the MongoDB use cases are
sufficiently rare and specialized that warning for them is acceptable even
though the code is safe.  The warnings are easy to avoid, either by following
the suggestions, or by suppressing it by one of the techniques I mentioned. 
This might even provide an opportunity to improve the code.  Expert programmers
should have no problem with that.  Relaxing the warning, on the other hand,
would compromise its goal at the expense of less experienced or less careful
programmers.

As an aside, using assignment and copy constructors should be at least as
efficient as calling memset and memcpy, and ideally more, and they should
always be preferred over the raw memory functions.  If/where they aren't as
efficient please open bugs for missing optimizations.


More information about the Gcc-bugs mailing list