1.4Move Semantics for const Objects

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();
引用和指针肯定不受影响

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值