对象优化及右值引用优化(三)
右值与左值
- 左值:有名字有内存
- 右值:没名字没内存,比如临时量
举例
class MyCString {
public:MyCString(const char* str = nullptr) {cout << "MyCString:: MyCString(const char* str)" << endl;if (str != nullptr){mptr = new char[strlen(str) + 1];strcpy(mptr, str);}else{mptr = new char[1];mptr[0] = '\0';}}~MyCString(){cout << "MyCString:: ~MyCString()" << endl;delete[]mptr;mptr = nullptr;}MyCString(const MyCString& rhs){cout << "MyCString::MyCString(const MyCString& rhs)" << endl;mptr = new char[strlen(rhs.mptr) + 1];strcpy(mptr, rhs.mptr);}MyCString& operator=(const MyCString& rhs){cout << "MyCString::operator=(const MyCString& rhs)" << endl;if (this == &rhs){return *this;}delete[]mptr;mptr = new char[strlen(rhs.mptr) + 1];strcpy(mptr, rhs.mptr);return *this;}MyCString(MyCString&& rhs){cout << "MyCString:: MyCString(MyCString&& rhs)" << endl;mptr = rhs.mptr;rhs.mptr = nullptr;}MyCString& operator=(MyCString&& rhs){cout << "MyCString:: operator=(MyCString&& rhs)" << endl;mptr = rhs.mptr;rhs.mptr = nullptr;return *this;} const char* c_str()const {return mptr;}
private:char* mptr;
};MyCString getCStr(MyCString& str)
{const char* tmpstr = str.c_str();MyCString tmpStr(tmpstr);return tmpStr;
}int main()
{int c = 10;int& d = c;int&& e = 20;cout << e << endl;MyCString str1("World");MyCString&& str = MyCString("Hello"); // 右值引用是个左值str1 = str;return 0;
}
右值引用
右值引用是用&&
符号表示的引用类型,允许我们绑定到右值上。这使得我们可以直接操作右值所拥有的资源,而不是拷贝它们
引用折叠
- & + && = &
- && + && = &&
移动语义与类型完美转发
std::move
,移动语义直接得到右值类型std::forward
, 类型完美转发能够识别左值与右值