class MyString {
public:
friend ostream& operator<<(ostream &out, const MyString &str);
MyString(const char *s) {
assert(s != NULL);
cout << "Constructor" << endl;
int sz = strlen(s);
str = new char[sz + 1];
strcpy(str, s);
}
MyString(const MyString &other) {
cout << "Copy Constructor" << endl;
int sz = strlen(other.str);
str = new char[sz + 1];
strcpy(str, other.str);
}
MyString(MyString &&other) {
cout << "rv Copy Constructor" << endl;
str = other.str;
other.str = NULL;
}
MyString &operator=(const MyString &other) {
cout << "operator=" << endl;
if (this == &other) return *this;
if (str != NULL) {
delete[] str;
str = NULL;
}
int sz = strlen(other.str);
str = new char[sz + 1];
strcpy(str, other.str);
return *this;
}
MyString &operator=(MyString &&other) {
cout << "rv operator=" << endl;
str = other.str;
other.str = NULL;
return *this;
}
~MyString() {
cout << "Destructor" << endl;
if (str != NULL) {
delete[] str;
str = NULL;
}
}
public:
char *str;
};
ostream& operator<<(ostream &out, const MyString &str) {
out << str.str;
return out;
}
int main()
{
vector<MyString> vs;
vs.reserve(10); //避免vector的内部移动影响下面的结果
vs.push_back(MyString("abc"));
cout << endl;
MyString sa("xyz");
vs.push_back(sa);
cout << endl;
MyString sb("lmn");
vs.push_back(move(sb));
cout << endl;
for_each(vs.begin(), vs.end(), [](MyString &str) {cout << str << endl;});
system("pause");
return 0;
}
运行结果:
Constructor
rv Copy ConstructorDestructor
Constructor
Copy Constructor
Constructor
rv Copy Constructor
abc
xyz
lmn
vector#push_back函数包含2个重载:
void push_back(T &v)和void push_back(T &&v)
当参数v为右值且包含转移构造函数时,调用后者,否则调用前者
第一个MyString是个临时对象(无名),故调用vector#push_back(MyString &&v)函数
第二个MyString是个左值,故调用vector#push_back(MyString &v)
第三个MyString是个左值通过move转为右值(调用者必须认识到MyString sb内部已发生变化,后面谨慎使用或不使用),故调用vector#push_back(MyString &&v)
move函数将左值转为右值,其效果与强制转换一样即也可以vs.push_back((MyString &&)sb);
————————————————————————————————————————————————
将前述代码main()中vs.reserve(10);一句注释掉后:
Constructor
rv Copy Constructor
Destructor
Constructor
rv Copy Constructor
Destructor
Copy Constructor
Constructor
rv Copy Constructor
rv Copy Constructor
Destructor
Destructor
rv Copy Constructor
abc
xyz
lmn
由于vector内部以2的幂进行长度扩展,在扩展时,必须进行对象的重新构造,这里使用转移构造函数后,重新构造对象的开销大大降低。
在第二个MyString传入后,vector重新生成一个长度为2的动态数组,并将原来的vector中的第一个元素复制过来,vector内部为减少开销使用了转移构造函数,故多了一对rv Copy Constructor和Destructor
在第三个MyString传入后,vector重新生成一个长度为4的动态数组,并将原来的vector中的第一、二个元素复制过来,故多了2对rv Copy Constructor和Destructor
如果没有MyString没有转移构造函数,则调用拷贝构造函数,其开销将非常巨大。