Reputation: 71
Below is my code
#include<iostream>
#include<string.h>
using namespace std;
class mystring {
private:
char * ptr;
public:
mystring() {
ptr = new char[1];
ptr[0] = '\0';
}
mystring(const char * obj) {
cout<<"param called "<<endl;
int len = strlen(obj);
ptr = new char[len+1];
strcpy(ptr,obj);
}
mystring(mystring& obj) {
cout<<"copy called "<<endl;
ptr = new char[strlen(obj.ptr)+1];
strcpy(ptr, obj.ptr);
}
mystring(mystring&& obj) noexcept{
cout<<"shallow copy created "<<endl;
ptr = obj.ptr;
obj.ptr = NULL;
}
friend ostream& operator<<(ostream& out, mystring& obj) {
out<<obj.ptr<<endl;
return out;
}
};
int main() {
mystring s1 = move("Hello World");
mystring s2 = s1;
return 0;
}
When I say mystring s1 = move("Hello World");
My understanding is that move ctor should be invoked but for some reason the output of the above code is param called copy called
. I am not sure why param ctor is getting invoked for that when I am trying to do a shallow copy. Can somebody help me understanding the output please. Thanks!
Upvotes: 0
Views: 56
Reputation: 16242
In the line
mystring s1 = move("Hello World");
you are move
ing the string literal "Hellow Word"
, not an object of type mystring
.
int main() {
mystring s1 = move("Hello World"); // moving a c-string, not very useful
mystring s2 = s1; // calls copy constructor
mystring s3 = std::move(s1); // new line, calls move constructor
return 0;
}
will print
param called
copy called
shallow copy created
https://godbolt.org/z/cxh7qrzcd
Finally, note the the "shallow copy" is not at all a good description of what move doest.
Upvotes: 3