Why should optional<T&> rebind on assignment?

孤者浪人 提交于 2019-12-01 02:26:09

What is the argument that opt = j should rebind the underlying reference?

I don't know what "the argument" you're looking for is. But you've just presented "an argument" for it:

optional<T&> opt;
opt = i;
opt = j;

Now, pretend that the second and third lines are far from each other. If you're just reading the code, what would you expect opt = j to do? Or more to the point, why would you expect its behavior to differ from opt = i?

To have the behavior of a wrapper type differ so drastically based purely on its current state would be very surprising.

Furthermore, we already have a way to communicate that you want to change the value inside the optional. Namely: *opt = j. This works just as well for optional<T&> as it does for optional<T>.

The way optional works is very simple: it's a wrapper type. Like any currently existing wrapper types, operations on them affect the wrapper, not the thing being wrapped. To affect the thing being wrapped, you explicitly use * or -> or some other interface function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!