之前不会。看了一下讨论,还是不要move shared_ptr了,只有能保证线程安全时才move。
原则上只要是后续不再需要的对象,传给别的函数,或者赋值给别的对象,都用std::move。
一般我只对比较重/大的对象、没有源码的对象用std::move。这个shared_ptr我知道它里面没几个字段。
因为我如果没这个类的源码,不知道这个类/对象的copy ctor和move ctor的性能开销,只能做一般的假定:move ctor更轻巧一些,性能更好。
shared_ptr<>这个当然有源码,在VC里的实现,其move ctor是4条整型赋值语句,copy ctor是2条整型赋值语句,加一条较重的InterlockedIncrement。
template <class _Ty2>
void _Move_construct_from(_Ptr_base<_Ty2>&& _Right) noexcept {
// implement shared_ptr's (converting) move ctor and weak_ptr's move ctor
_Ptr = _Right._Ptr;
_Rep = _Right._Rep;
_Right._Ptr = nullptr;
_Right._Rep = nullptr;
}
template <class _Ty2>
void _Copy_construct_from(const shared_ptr<_Ty2>& _Other) noexcept {
// implement shared_ptr's (converting) copy ctor
_Other._Incref();
_Ptr = _Other._Ptr;
_Rep = _Other._Rep;
}
顶楼里Raymond Chen的那个例子,传参move走后还用到了被move走的对象,就算没有求值顺序问题,也最好不要move。
Rust里默认就是move,而且move走的了变量是不可能再让你使用的,已经帮广大码农提高了下限了,只要不乱调用clone。
【 在 DoorWay 的大作中提到: 】
: 你说的我都知道。
: 我问的就是,你,实际的你,写这段代码,加这个move不?
--
修改:z16166 FROM 114.245.195.*
FROM 114.245.195.*