CPP技术总结

类对象内存模型

举个栗子:

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1:new delete 与 malloc free的区别 1-> new是C++运算符,malloc是C的库...
    已二锅阅读 2,490评论 1 6
  • 技术交流QQ群:1027579432,欢迎你的加入! 一.static关键字的作用 1.静态成员的特点 1.sta...
    CurryCoder阅读 2,976评论 3 3
  • 一、C语言基础 1、struct 的内存对齐和填充问题其实只要记住一个概念和三个原则就可以了: 一个概念:自然对齐...
    XDgbh阅读 2,250评论 1 38
  • 本文按照 cppreference[https://en.cppreference.com/w/] 列出的特性列表...
    401阅读 21,825评论 2 18
  • 以下是我最近几个星期学习c++11做的一些记录,包括收集的一些信息,整理的相关概念和写的一些测试代码。具体相关代码...
    在河之简阅读 2,886评论 0 6