隐式生成的赋值运算符应该是 &ref 资格? [英] Should implicitly generated assignment operators be & ref-qualified?

查看:31
本文介绍了隐式生成的赋值运算符应该是 &ref 资格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在 gcc 4.8.1 上编译没有问题:

The following code compiles without problem on gcc 4.8.1:

#include <utility>

struct foo
{
};

int main()
{
    foo bar;

    foo() = bar;
    foo() = std::move( bar );
}

似乎为 foo 隐式生成的赋值运算符不是 & ref-qualified,因此可以在右值上调用.根据标准,这是正确的吗?如果是这样,有什么理由要求隐式生成的赋值运算符是 & ref-qualified?

It seems the implicitly generated assignment operators for foo are not & ref-qualified and so can be invoked on rvalues. Is this correct according to the standard? If so, what reason is there for not requiring implicitly generated assignment operators to be & ref-qualified?

为什么标准不要求生成以下内容?

Why doesn't the standard require the following to be generated?

struct foo
{
  foo & operator=( foo const & ) &;

  foo & operator=( foo && ) &;
};

推荐答案

好吧,分配给右值有一些合法的用例.引用 Ref-qualifiers for assignment标准库中的运算符:

Well, there are certain legitimate use cases for assigning to an rvalue. To quote from Ref-qualifiers for assignment operators in the Standard Library:

只有几种非常具体的类型才有意义支持分配给右值.特别是,作为代理,例如,vector<bool>::reference,以及其赋值的类型运算符是 const 限定的(例如,slice_array).

There are only a few very specific types for which it makes sense to support assigning to an rvalue. In particular, types that serve as a proxy, e.g., vector<bool>::reference, and types whose assignment operators are const-qualified (e.g., slice_array).

C++ 标准委员会显然认为默认赋值不应具有隐式 ref 限定符 - 而是应该显式声明.事实上,如果突然间所有隐式声明的赋值运算符都不适用于右值,则可能存在现有代码将停止工作.

The C++ standard committee obviously felt that default assignment should not have an implicit ref qualifier - rather it should be explicitly declared. Indeed, there may be existing code which would stop working if all of a sudden all implicitly declared assignment operators didn't work with rvalues.

诚然,设计一个我们希望隐式声明的赋值运算符与右值一起工作的示例有点困难,但是 C++ 标准委员会可能不想在保留向后兼容性方面冒险.代码如下:

Granted, it's a bit hard to contrive an example where we want an implicitly declared assignment operator to work with rvalues, but the C++ standard committee likely doesn't want to take these kind of chances when it comes to preserving backwards compatibility. Code like this:

int foo_counter = 0;

struct Foo
{
    Foo()
    {
        ++foo_counter;
    }

    ~Foo()
    {
        --foo_counter;
    }
};

int main()
{
    Foo() = Foo();
}

...不会再工作了.归根结底,标准委员会希望确保以前有效的 C++(无论多么愚蠢或做作)继续在 C++11 中工作.

...wouldn't work anymore. And at the end of the day, the standards committee wants to make sure that previously valid C++ (no matter how stupid or contrived) continues to work in C++11.

这篇关于隐式生成的赋值运算符应该是 &amp;ref 资格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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