c++ std::move详解

c++ std::move详解

img

img

在移动构造中的时候,移动拷贝其实就是把原来参数对象的指针地址给到了构造的对象,再把原先对象的指针置为NULL,这样内存就不会被原来函数给析构了。对于实体的对象执行的其实也是拷贝构造。

&&是可以直接对目标进行直接操作的,对操作者是可见的,不是副本

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

class Str {
 public:
  char *str;
  Str(char value[]) {
    cout << "普通构造函数..." << endl;
    str = NULL;
    int len = strlen(value);
    str = (char *)malloc(len + 1);
    memset(str, 0, len + 1);
    strcpy(str, value);
  }
  Str(const Str &s) {
    cout << "拷贝构造函数..." << endl;
    str = NULL;
    int len = strlen(s.str);
    str = (char *)malloc(len + 1);
    memset(str, 0, len + 1);
    strcpy(str, s.str);
  }
  Str(Str &&s) {
    cout << "移动构造函数..." << endl;
    str = NULL;
    str = s.str;
    s.str = NULL;
  }
  ~Str() {
    cout << "析构函数" << endl;
    if (str != NULL) {
      free(str);
      str = NULL;
    }
  }
};

class f {
 public:
  f() {}
  explicit f(int &&a) {
    a = a + 1;
    b = a;
  }
  ~f() {}
  void get() { std::cout << "value: " << b << std::endl; }

 private:
  int b;
};

int main() {
  char value[] = "I love zx";
  Str s(value);
  vector<Str> vs;
  vs.push_back(move(s));
  //   vs.push_back(s);
  cout << vs[0].str << endl;
  if (s.str != NULL) cout << s.str << endl;
  // return 0;

  int a = 10;

  int b = std::move(a);

  std::string c("hello");
  std::string d = std::move(c);
  // &a = NULL;

  f object(std::move(a));

  std::cout << " a: " << a << std::endl;
  object.get();
  std::cout << " b: " << b << std::endl;

  std::cout << " c: " << c << std::endl;
  std::cout << " d: " << d << std::endl;
}

结果

普通构造函数...
移动构造函数...
I love zx
 a: 11
value: 11
 b: 10
 c: 
 d: hello
析构函数
析构函数

参考链接

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值