So, I've just recently discovered rvalue references in C++11, and I don't think I quite get it. Let's say I was making a wrapper class around
std::string
with the following code.
1 2 3 4 5 6 7 8 9 10 11
|
class String
{
private:
std::string str;
public:
String() {}
String(const char* s);
String(String&& s);
String(const String& s);
};
|
Now, say I create a string using the following code:
1 2 3
|
String str = String("Hello!");
// yes, this is redundant since I could just pass a
// const char* to [str] directly, but ignore that
|
Here,
String("Hello!")
is a temporary object that only exists until the semicolon and therefore also an rvalue.
str
, however, is an lvalue. This means that this will call
String(String&& s)
as the constructor rather than
String(const String& s)
.
While the class can function without
String(String&& s)
, it can't function without
String(const String& s)
, the copy constructor (ignoring the fact that the compiler will automatically generate one in this case). Now, if
str
was initialized with the fourth constructor rather than the third, if I understand it correctly,
String("Hello!")
will be created as a temporary value, and then its contents will be
copied rather than
moved to [str], which seems unneccessary in such cases.
I have two questions:
A) Have I understood these concepts correctly? If not, what am I misunderstanding?
B) Is there any other kind of constructor I should create? When is it appropriate to use lvalue references versus rvalue references?
I would greatly appreciate any help you could give.