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

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

问题描述

以下代码在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 && ) &;
};


推荐答案

一个右值。引用 作业的参考限定符标准库中的运算符:

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


只有几种非常具体的类型,
支持赋值到右值。特别地,用作
代理的类型,例如向量< bool> ::引用,以及其赋值
运算符是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限定符, / em>。事实上,如果突然间所有隐式声明的赋值运算符都不能使用右值,那么可能存在现有的代码会停止工作。

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-qualified?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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