为什么可选< T&>重新分配作业? [英] Why should optional<T&> rebind on assignment?

查看:67
本文介绍了为什么可选< T&>重新分配作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于optionalvariant应该如何处理引用类型,尤其是在赋值方面,一直存在争论.我想更好地了解围绕这个问题的辩论.

There is an ongoing debate about what optional and variant should do with reference types, particularly with regards to assignment. I would like to better understand the debate around this issue.

optional<T&> opt;
opt = i;
opt = j; // should this rebind or do i=j?

当前,决定是使optional<T&>格式错误,而使variant::operator=格式错误(如果任何类型是引用类型)-避开该参数并仍然为我们提供大部分功能.

Currently, the decision is to make optional<T&> ill-formed and make variant::operator= ill-formed if any of the types is a reference type - to sidestep the argument and still give us most of the functionality.

opt = j 应该重新绑定基础引用的依据是什么?换句话说,为什么应该我们像这样实现optional:

What is the argument that opt = j should rebind the underlying reference? In other words, why should we implement optional like this:

template <class T>
struct optional<T&> {
    T* ptr = nullptr;

    optional& operator=(T& rhs) {
        ptr = &rhs;
        return *this;
    }
};

推荐答案

opt = j应该重新绑定基础引用的论点是什么?

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;

现在,假装第二行和第三行彼此远离.如果您只是在阅读代码,您期望opt = j会做什么?或更重要的是,为什么您希望它的行为不同于opt = i?

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.

此外,我们已经有了一种交流方式,您可以在optional内更改 值.即:*opt = j.对于optional<T&>来说,它和optional<T>一样好.

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>.

optional的工作方式非常简单:它是包装器类型.像任何当前现有的包装器类型一样,对其进行的操作会影响 wrapper ,而不影响被包装的东西.要影响被包裹的东西,可以显式使用*->或其他一些接口函数.

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.

这篇关于为什么可选&lt; T&amp;&gt;重新分配作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆