C++ Logo

std-proposals

Advanced search

[std-proposals] readonly specifier

From: Alexander Christensen <alex_c007_at_[hidden]>
Date: Wed, 20 Dec 2023 15:15:51 +0000
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.

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

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.

// Alexander


Received on 2023-12-20 15:15:54