C++ Logo

std-proposals

Advanced search

Re: Yet another member function for std::map

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 2 Aug 2021 10:18:15 -0400
On Mon, Aug 2, 2021 at 6:26 AM Andrey Semashev via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> On 8/2/21 12:28 PM, Lénárd Szolnoki via Std-Proposals wrote:
> >
> > The Achilles' heel of optional<T&> seems to be assignment. I'm of the
> > opinion that it simply shouldn't have assignment from arguments of type
> > T, but I believe there is no perfect answer.
>
> Personally, I have no problem with rebinding semantics of
> optional<T&>::operator=(T&). That it would affect the referred object
> makes no sense because (a) there may not be such an object (if the
> optional is empty) and (b) no other version of optional<T> acts this
> way.

Um, yes they do. If you have an engaged `optional<T>`, and you assign
a `T` to it, it assigns to the engaged value. It does not
unengage/re-engage itself.

So if you have this:

```
optional<T> t = ...; //some T
T& t_ref = *t;
t = ...; //some other T
```

If each of those pieces of code is valid, then `t_ref` is also valid.
It still refers to the value you assigned to the `t`.

The semantics you want for `optional<T&>` violate this. The `t_ref` in
this case would refer to the old referenced object, not the new one.


> In order to access the referred object one has to use operator* or
> operator-> or similar accessors, and assignment is no exception.
>
> Having the assignment is important to be able to initialize an empty
> optional. Yes, you could assign from a temporary optional, but that is
> unnecessarily verbose, IMHO. In any case, this is not the reason to not
> have optional<T&> at all.

Received on 2021-08-02 09:18:28