2.2 std::move()

1. std::move()

①我们都知道 对象都有生命周期,当生命周期结束的时候,对象会被销毁释放

②我们可以在一个对象生命周期没有结束的时候,我们可以对一个对象使用move标记,来表示 我不在需要这个对象了,仅使用std::move()并没有真的被move,只是作为一个标记

void foo(const std::string& lr); 
// binds to the passed object without modifying it

void foo(std::string&& rv);
 // binds to the passed object and might steal/modify the value
...
std::string s{"hello"};
...
foo(s); // calls the first foo(), s keeps its value

foo(std::move(s)); 
// calls the second foo(), s might lose its value

2. std::move(obj) 也可以传给一个左值参数

void foo(const std::string& lr); 
// binds to the passed object without modifying it

... // no other overload of foo()
std::string s{"hello"};
...
foo(s); // calls the first foo(), s keeps its value

foo(std::move(s)); // also calls the first foo(), s keeps its value

foo函数没有第二个重载了
当找不到右值形参的函数时候,就会调用左值形参的函数

3.std::move()不能传递给一个non-const 的左值

void foo(std::string&); // modifies the passed argument
...
std::string s{"hello"};
...
foo(s); // OK
foo(std::move(s)); // ERROR

foo(std::move(s)); // ERROR

4.

foo(static_cast<std::string&&>(s)); 
// same effect as foo(std::move(s))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值