#include <iostream>
using namespace std;
#include <cstring>
class Word{
private:
char* ptr = nullptr;
public:
Word(){
cout << "default constructor" << endl;
}
Word(const char* sentence):ptr{new char [strlen(sentence)+1]}{
strcpy(ptr, sentence);
cout << "conversion constructor: " << ptr << endl;
}
Word(const Word& w):ptr{new char [strlen(w.ptr)+1]}{
strcpy(ptr, w.ptr);
cout << "copy constructor: "<< ptr << endl;
}
~Word(){
cout << "destructor: " << ptr << endl;
}
};
int main(){
Word a ("A stands for apple!");
Word&& b = "B stands for Banana, rvalue ref";
b = a;
}
My Eclipse result:
conversion constructor: A stands for apple!
conversion constructor: B stands for Banana, rvalue ref
destructor: A stands for apple!
destructor: A stands for apple!
My Extectation:
conversion constructor: A stands for apple!
conversion constructor: B stands for Banana, rvalue ref
destructor: B stands for Banana, rvalue ref
destructor: A stands for apple!
destructor: A stands for apple!
I am confused by this step.
b = a;
When a is assigned to b, it could suppose to first destruct the temporary object (with cstring of "B stands for Banana, rvalue ref") that b is holding, then assign the value of a to b. Why in the Eclipse's result, it does not perform the destruction of the temporary object?
b = a;is invoking the assignment operator, not the copy constructor. If explicitly deleted, the code won't compile:The compilation line:
The compiler will provide a default assignment operator, so the code in your question is leverage that. To see what's happening, add copy-assignment and move-assignment operators.
With these in place, I get the expected output:
As an aside, you're leaking memory. Your destructor should look like this:
You could also implement the assignment operator using the copy/swap idiom (below). This will add an extra constructor/destructor output due to the temporary, but it's good practice overall.