I have a string class. Some operators return references, others return values. Only the ones that return values can take advantage of the rvalue copy constructor or rvalue assignment operator.
I would like the rvalue operator to be called on a reference to an rvalue.
Given these:
String(const TCHAR* sz);
String(const String& s);
String& operator+=(const TCHAR* sz);
String& operator=(String&& r);
And this code:
String x;
x = (String("fred") += "foo");
It calls the copy constructor, the += operator, but then the COPY CONSTRUCTER again. I want it to call the rvalue assignment operator!
I added this:
String(String&& r)
And that makes no difference.
EDIT:
I confirmed that if I make my += operator return a value, the rvalue assignment operator will be called. I have done a lot of performance testing and doing this makes everything a lot slower.
You can’t easily differentiate between a “genuine” rvalue and an rvalue reference, but you don’t seem to have a motivation to do so. Your overload is fine.
The problem is that rvalue-ness is lost by the
+=operator. There are three solutions:x = std::move(String("fred") += "foo");Use non-member overloads. I generally prefer this because it resolves other issues such as applying conversion functions to the left-hand side of a
+=expression.Use reference qualifiers so that
operator+=returns an rvalue when applied to an rvalue. Few compilers support this yet.