C++ Logo

std-proposals

Advanced search

Re: [std-proposals] readonly specifier

From: Bo Persson <bo_at_[hidden]>
Date: Wed, 20 Dec 2023 17:24:11 +0100
On 2023-12-20 at 16:15, Alexander Christensen via Std-Proposals wrote:
> I have been wondering if there could be some benefits in introducing a
> 'readonly' specifier for class member fields. The basic idea is this
> example:
>
> class FloatRange
> {
> public:
> FloatRange() : _min(0.0f), _max(0.0f) {}
> FloatRange(float min, float max) : _min(std::min(min,max)),
> _max(std::max(min,max)) {}
> FloatRange(const FloatRange& fr) : _min(fr._min), _max(fr._max) {}
>
> // possibility 1
> FloatRange& operator=(const FloatRange& fr) : _min(fr._min),
> _max(fr._max) {}
> // possibility 2
> FloatRange& operator=(const FloatRange& fr) { _min = fr._min; _max
> = fr._max; }
>
> float clamp(float val) const { return std::clamp(val, _min, _max); }
>
> private:
> readonly float _min;
> readonly float _max;
> };
>
> Normally I'd use 'const' specifier for the two private fields, since I
> would like _some guarantee_ they cannot be modified after creation.
> However, 'const' is a problem for the assignment operator.

Yes, because that would modify the fields. :-)

Why is assignment allowed to modify, but nothing else?

>
> So I write in suggestion for a kind of middle-ground, where readonly is
> less restrictive than const, but more restrictive than unspecified fields.

Perhaps it should then be assignonly? It isn't really readonly if it
sometimes is written.


>
> Has this been suggested before, and what are benefits/drawbacks?
>
> Alternatively to polluting the standard with more keywords, perhaps we
> could add support for "whatever-the-syntax-is-called" (?), where we
> place a colon and field initializers, for the assignment operator as well.

Yes, but...

The "colon initializers" are used for initialization (creates a value),
like a copy constructor, but not for assignment (changes a value).


Also, is this a use case/problem big enough to spend the work needed to
change the language? Does it solve a lot of problems, or just some
inconvenience?

Received on 2023-12-20 16:24:20