C++ move semantics

  1. Move casts the argument to rvalue reference, and forward casts the argument to the value type it is bound to. The cast doesn’t move, doesn’t change the obj itself and does nothing but let the compiler know this is an rvalue.
  2. Move semantics happens for move constructor and move assignment overloading when you pass an rvalue obj to them.
  3. For an rvalue reference argument in a function, you can only pass non-const rvalue to it. (otherwise compile time error) (std::move cannot change constness). This is only a reference, and doesn’t call move constructor.
  4. For an lvalue reference argument, you cannot pass rvalue to it (compile time error). But for a const lvalue reference argument, you can pass const or non-const rvalue to it.
  5. Use rvalue references as function arguments when you want to specifically enable and encourage move semantics for performance reasons or when implementing perfect forwarding. An argument being an rvalue reference does not automatically trigger move semantics; move operations must be explicitly invoked using std::move.
  6. Move semantics is useful because it avoids copying the obj (temporarily doubled memory usage and copy overhead). It’s also useful for unique_ptr and shared_ptr.
  7. Forward is useful because it can maintain the value type of the input arguments and thus benefit generic template programming since you can pass in both lvalue and rvalue reference.
  8. For forward, the argument must be T&& or auto&&. Once an rvalue reference parameter is passed in like void func(Widget&& x) or void func(T&& x), x will become an lvalue since everything with a name is lvalue. But “T” can encode the value type by which x is initialized. So if you use forward, it can cast x back to an rvalue reference.
  9. Move semantics can be useful when you want to transfer the ownership or return value.
  10. Compiler will usually apply RVO or NRVO to optimize return value by directly constructing the returned value in the caller’s scope, which is even faster than doing move operation. It can also sometimes automatically invoke move operation if possible. So it’s not advised to explicitly invoke move operation in return value unless the compiler cannot handle it and chooses to use copy.
  11. Move constructor or assignment through std::move or std::forward will leave the original lvalue being valid but unspecified.

Other Tips: The explicit keyword is a valuable tool in C++ for controlling how constructors and conversion operators are invoked, preventing implicit conversions that can lead to subtle bugs or unintended behavior. By making conversions explicit, programmers can write safer, clearer, and more maintainable code.

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值