Move ctor 没有被调用
Move ctor is not getting invoked
下面是我的代码
#include<iostream>
#include<string.h>
using namespace std;
class mystring {
private:
char * ptr;
public:
mystring() {
ptr = new char[1];
ptr[0] = '[=10=]';
}
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;
}
当我说 mystring s1 = move("Hello World");
时,我的理解是应该调用 move ctor,但由于某种原因,上述代码的输出是 param called copy called
。我不确定为什么在尝试进行浅拷贝时会为此调用 param ctor。有人可以帮我理解输出吗?谢谢!
在行
mystring s1 = move("Hello World");
您正在 move
字符串文字 "Hellow Word"
,而不是 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;
}
将打印
param called
copy called
shallow copy created
https://godbolt.org/z/cxh7qrzcd
最后,请注意“浅拷贝”根本不能很好地描述移动的目的。
下面是我的代码
#include<iostream>
#include<string.h>
using namespace std;
class mystring {
private:
char * ptr;
public:
mystring() {
ptr = new char[1];
ptr[0] = '[=10=]';
}
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;
}
当我说 mystring s1 = move("Hello World");
时,我的理解是应该调用 move ctor,但由于某种原因,上述代码的输出是 param called copy called
。我不确定为什么在尝试进行浅拷贝时会为此调用 param ctor。有人可以帮我理解输出吗?谢谢!
在行
mystring s1 = move("Hello World");
您正在 move
字符串文字 "Hellow Word"
,而不是 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;
}
将打印
param called
copy called
shallow copy created
https://godbolt.org/z/cxh7qrzcd
最后,请注意“浅拷贝”根本不能很好地描述移动的目的。