Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 );
}

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 && ) &;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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.

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();
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...