C++ Logo

std-discussion

Advanced search

Re: Is [[indeterminate]] not applicable to data members?

From: Brian Bi <bbi5291_at_[hidden]>
Date: Tue, 11 Mar 2025 16:00:46 -0400
>
> >I'm uncomfortable with the idea of a class author being able to override
> >the user's choice to *not* declare a local variable [[indeterminate]], by
> >placing [[indeterminate]] on the declaration of a non-static data member
> >and thus making part of the object's storage indeterminate anyway. Note
> >that even if it's just in a private member, there will still be UB if the
> >object is used as the source of `memcpy`.
>
> It's the class author's job to do the proper encapsulation. If memcpy is
> indeed UB (is it really?), then maybe such classes must not be trivially
> copyable. I agree that it's error prone, but if a class requires some
> indeterminate storage for efficient operation, then it could be less error
> prone to implement it correctly once within the class than the user
> applying [[indeterminate]] at each usage.


My mistake, my earlier message was inaccurate. The `memcpy` itself would
not be UB, but examining the resulting `unsigned char` array (or whatever
it is) would cause UB.

But I think that it's not UB to use `memcpy` even when the source is a
non-trivially-copyable class. We just place no guarantees on what you get.
But I don't interpret this as a blanket permission to treat the bytes as
indeterminate. In P1839, we use the wording "an unspecified value that is
neither indeterminate nor erroneous".

(Now, strictly speaking, storage that is not indeterminate initially could
become indeterminate later, e.g., the class's constructor could create an
indeterminate array on the stack and then memcpy that array into one of its
own members, thus giving the member an indeterminate value. So that means
the class author is still ultimately in control, and the user can never be
sure whether they're getting indeterminate bytes after construction. But
despite that, I think it would be wise not to *encourage* class authors to
give their class members indeterminate values if they didn't initially have
them.)
-- 
*Brian Bi*

Received on 2025-03-11 20:01:10