关于string的移动构造
在观察string移动构造时发现一个问题,为什么移动构造前后原来应该被置空的对象的c_str()没有变化,而且新构造的对象的c_str()和原对象不等呢?我期望的行为应该和我自己实现的String对象的行为类似啊
程序代码:
#include "bits/stdc++.h" using namespace std; class String { public: String() { cout << "String()" << endl; } String(const char* p) { cout << "String(const char* p)" << endl; this->len = strlen(p); this->p = new char[this->len + 1]; strcpy(this->p, p); } String(const String& s) { cout << "String(const String& s)" << endl; this->len = s.len; this->p = new char[this->len + 1]; strcpy(this->p, s.p); } String(String&& s) { cout << "String(String&& s)" << endl; this->len = s.len; this->p = s.p; s.p = nullptr; s.len = 0; } ~String() { cout << "~String()" << endl; if(this->p) { delete this->p; } } String& operator = (const String& s) { cout << "String& operator = (const String& s)" << endl; if(this->p) { delete this->p; } this->len = s.len; this->p = new char[this->len + 1]; strcpy(this->p, s.p); return *this; } String& operator = (String&& s) { cout << "String& operator = (String&& s)" << endl; if(this->p) { delete this->p; } this->len = s.len; this->p = s.p; s.p = nullptr; s.len = 0; return *this; } const char* c_str() const { return p; } private: char* p = nullptr; int len = 0; friend ostream& operator << (ostream& out, const String& s); }; ostream& operator << (ostream& out, const String& s) { if(s.c_str()) { out << s.c_str(); } else { out << ""; } return out; } void test1() { String a = "abc"; printf("%p\n", a.c_str()); String b = move(a); printf("%p\n", a.c_str()); printf("%p\n", b.c_str()); cout << a << endl; cout << b << endl; move(b); cout << b << endl; } void test2() { using String = std::string; String a = "abc"; printf("%p\n", a.c_str()); String b = move(a); printf("%p\n", a.c_str()); printf("%p\n", b.c_str()); cout << a << endl; cout << b << endl; move(b); cout << b << endl; } int _main_() { test1(); test2(); return 0; }