美文网首页
CPP技术总结

CPP技术总结

作者: dajielailin | 来源:发表于2023-06-21 11:18 被阅读0次

    类对象内存模型

    举个栗子:

    Struct A {
        A(): pData(new int) {}
        A(const A& rhs);
        A& operator=(const A& rhs);
        A(const A&& rhs);
        A& operator=(const A&& rhs);
        ~A();
        Virtual test() {cout << “A” <<endl;}
    Private:
        Int* pData;
    }
    

    拷贝构造和拷贝赋值

    使用场景:参数对象拷贝后还需要引用或使用。

    拷贝构造

    定义了使用同类型的另一对象初始化本对象的操作。

    A::A(const A& rhs): pData(null) {
        If(rhs.pData != null)
        {
            pData = new int(rhs->pData);
        }
    }
    

    拷贝赋值

    定义了将一个对象赋予同类型新对象的操作。

    A& A::operator=(const A& rhs) {
        If(this == &rhs) return *this;
        If(rhs.pData != null) 
        {
            Int* temp = new int(rhs->pData);    //临时变量是为了防止new申请内存失败
            If(pData != NULL) 
            {
                Delete pData; //由于要指向新对象,故要释放掉旧内存
            }
            pData = temp;
    
        }
    }
    

    移动拷贝构造和移动拷贝赋值

    使用场景:参数对象拷贝后不再被引用或使用。

    移动拷贝构造

    A::A(const A&& rhs): pData(rhs.pData) noexcept
    //若移动操作不会被异常打断,则需要noexcept通知标准库
    {
        Rhs.pData = null;
    }
    

    移动拷贝赋值

    A& A::operator(const A&& rhs) noexcept
    {
        If(this == &rhs) return *this;
        If(rhs.pData != NULL) 
        {
            If(pData != NULL)   delete pData;
            pData = rhs.pData; //移动操作窃取“资源”,通常不分配任何资源
            Rhs.pData = null;
        }
    }
    

    C11智能指针

    std::shared_ptr<T>

    特性介绍

    image.png

    常见误区

    image.png

    std::waek_ptr<T>

    特性介绍

    image.png

    std::unique_ptr<T>

    特性介绍

    image.png

    相关文章

      网友评论

          本文标题:CPP技术总结

          本文链接:https://www.haomeiwen.com/subject/fjguydtx.html