Trying to understand "&&"
I thought I understood the "&&" until the following simple example did
not work.
Can someone tell me which is the problem or what I did not understand?
It add 2 strings and "cout" the result.
Special thanks for your time!
------------------
g++ -std=c++0x main.cpp
------------------
-- main.cpp ------
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
A() : str(0) { cout << "A()" << endl; }
A(const char *string) : str(0) { str = new char[strlen(string) + 1];
strcpy(str, string); cout << "A(const char*)" << endl; }
~A() { delete[] str; cout << "~A()" << endl; }
A(A &a) : str(0) { str = new char[strlen(a.str) + 1]; strcpy(str,
a.str); cout << "A(A&)" << endl; }
A(A &&a) : str(0) { str = a.str; a.str = 0; cout << "A(A&&) : " << str
<< endl; }
A &operator=(A &a) {
delete[] str; str = 0;
str = new char[strlen(a.str) + 1];
strcpy(str, a.str);
cout << "A = &A" << endl;
return *this;
}
A &operator=(A &&a) {
delete[] str;
str = a.str; a.str = 0;
cout << "A = &&A" << endl;
return *this;
}
A &&operator+(A &a) {
A b;
b.str = new char[strlen(this->str) + strlen(a.str) + 1];
strcpy(b.str, this->str);
strcpy(b.str + strlen(this->str), a.str);
cout << "A + A = " << b.str << endl;
return std::move(b);
}
const char *operator*() { return str; }
protected:
char *str;
};
int main()
{
A a("Uni");
A b("verse");
A c = a + b;
cout << *c << endl;
cout << *(a+b) << endl;
return 0;
}
------------------