大佬教程收集整理的这篇文章主要介绍了c – 提供正确的移动语义,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
class big_and_complicated { // lots of complicated code }; class structure { public: structure() : m_data( new big_and_complicated() ) {} structure( structure && rhs ) : m_data( std::move( rhs.m_data ) ) { // Maybe do something to rhs here? } ~structure() { delete m_data; } private: big_and_complicated * m_data; } int main() { structure s1; structure s2( std::move( s1 ) ); return 0; }
根据我的理解,在std :: move(s1)到s2之后,唯一可以安全地在s1上做的就是调用它的构造函数.但是据我所知,这将导致删除析构函数中s1中包含的指针,使s2也无用.所以我猜我在std :: move()指针时必须做一些事情来渲染析构函数.据我所知,最安全的做法是在移动的对象中将其设置为0,因为这会在以后将删除变为无操作.到目前为止,这种推理是否正确?或者std :: move()实际上足够聪明,为我指出了指针,使其使用安全吗?到目前为止,我看到实际测试套件中没有崩溃,但我还没确定实际调用了move-constructor.
struct structure { structure() : m_data{new big_and_complicated{}} { } structure(structure&& rhs) : m_data{rhs.m_data} { rhs.m_data = nullptr; } structure& operator =(structure&& rhs) { if (this != &rhs) { delete m_data; m_data = rhs.m_data; rhs.m_data = nullptr; } return *this; } ~structure() { delete m_data; } private: big_and_complicated* m_data; structure(structure const&) = delete; // for exposition only structure& operator =(structure const&) = delete; // for exposition only }
更好的是,使用std :: unique_ptr< big_and_complicated>而不是big_and_complicated *,你不需要自己定义任何一个:
#include <memory> struct structure { structure() : m_data{new big_and_complicated{}} { } private: std::unique_ptr<big_and_complicated> m_data; }
最后,除非你真的希望结构保持不可复制,否则你最好只在big_and_complicated中实现正确的移动语义,并让结构直接保存big_and_complicated对象.
以上是大佬教程为你收集整理的c – 提供正确的移动语义全部内容,希望文章能够帮你解决c – 提供正确的移动语义所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。