1.Move Semantics for const Objects
被const修饰的对象 不能被move
move就是要修改传入的值,去"偷"
2.类的定义
class MyString
{
public:
MyString(int Len = 0, const char* Str = nullptr) : nLen{ Len }
{
cout << "默认构造函数" << endl;
pStr = new char[nLen + 1];
memcpy(pStr, Str, nLen + 1);
}
MyString(const MyString& Temp) : nLen{ Temp.nLen }
{
cout << "复制构造函数" << endl;
pStr = new char[nLen + 1];
memcpy(pStr, Temp.pStr, nLen + 1);
}
MyString(MyString&& Temp) noexcept :nLen{ Temp.nLen }, pStr{ Temp.pStr }
{
cout << "移动构造函数" << endl;
Temp.nLen = 0;
Temp.pStr = nullptr;
}
~MyString()
{
if (nullptr != pStr)
{
nLen = 0;
delete[]pStr;
}
}
friend ostream& operator<<(ostream& os, const MyString& Temp)
{
if (nullptr != Temp.pStr)
{
os << Temp.pStr;
}
return os;
}
private:
char* pStr;
int nLen;
};
3 代码1
MyString a(5, "Hello");
cout <<"a" << a << endl;
cout << "*******************" << endl;
MyString b = a;
cout << "a" << a << endl;
cout << "b" << b << endl;
cout << "*******************" << endl;
MyString c = std::move(a);
cout << "a" << a << endl;
cout << "b" << b << endl;
cout << "c" << c << endl;
运行结果

MyString a(5, “Hello”);
MyString c = std::move(a);
调用的是移动构造函数
4.代码2
const MyString a(5, "Hello");
cout <<"a" << a << endl;
cout << "*******************" << endl;
MyString b = a;
cout << "a" << a << endl;
cout << "b" << b << endl;
cout << "*******************" << endl;
MyString c = std::move(a);
cout << "a" << a << endl;
cout << "b" << b << endl;
cout << "c" << c << endl;

const MyString a(5, “Hello”);
MyString c = std::move(a);
调用的是拷贝构造函数
5.const Return Values
const会禁用移动语意,所以从C++11开始 不要在return const value
比如 这么干
const std::string getValue();
引用和指针肯定不受影响
本文探讨了C++中移动语义的基本概念,特别是在const对象上的应用。通过具体代码示例展示了移动构造函数与复制构造函数的区别,以及如何避免在返回值中使用const来启用移动语义。
476

被折叠的 条评论
为什么被折叠?



