Should named assignment operators be & ref-qual?

The following code compiles without problems in gcc 4.8.1:

#include <utility> struct foo { }; int main() { foo bar; foo() = bar; foo() = std::move( bar ); } 

It seems that the implicitly generated assignment operators for foo do not match & ref-qual and therefore can be called on rvalues. Is this correct according to the standard? If so, what is the reason for not requiring that the implicitly generated assignment operators be & ref-qual? A.

Why does the standard not require the creation of the following?

 struct foo { foo & operator=( foo const & ) &; foo & operator=( foo && ) &; }; 
+4
source share
2 answers

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

There are only a few very specific types for which the support assigns an rvalue. In particular, the types that serve as proxies, for example, vector <bool> :: reference, and the types whose purpose the operators have const qualification (for example, slice_array).

The C ++ Standardization Committee obviously believed that the default assignment should not have an implicit reflective qualifier - rather, it should be explicitly declared. Indeed, there may be existing code that will stop working if all of the implicitly declared assignment operators suddenly fail to work with rvalues.

Of course, it's a little hard to come up with an example where we want the implicitly assigned assignment operator to work with rvalues, but the C ++ standard committee probably doesn't want to accept such possibilities when it comes to maintaining backward compatibility. Code like this:

 int foo_counter = 0; struct Foo { Foo() { ++foo_counter; } ~Foo() { --foo_counter; } }; int main() { Foo() = Foo(); } 

... will no longer work. And at the end of the day, the standards committee wants to make sure that the previous C ++ (no matter how silly or far-fetched) continues to work in C ++ 11.

+5
source

It seems your question is more "Why is an assignment to rvalue ever useful?" and not "Why is the standard ref-qualify auto-generated constructors?"

Assigning a reason for rvalue is allowed because there are some cases where this is useful.

One example uses std::tie (link) :

 #include <set> #include <tuple> int main() { std::set<int> s; std::set<int>::iterator iter; bool inserted; // unpacks the return value of insert into iter and inserted std::tie(iter, inserted) = s.insert(7); } 

Example borrowed from cppreference.com, then modified

+1
source

Source: https://habr.com/ru/post/1485136/


All Articles