C++解析(31):自定义内存管理(完)

Wesley13
• 阅读 453

0.目录

1.遗失的关键字mutable

2.new / delete

3.new[] / delete[]

4.小结

5.C++语言学习总结

1.遗失的关键字mutable

笔试题: 统计对象中某个成员变量的访问次数

遗失的关键字:

  • mutable是为了突破const函数的限制而设计的
  • mutable成员变量将永远处于可改变的状态
  • mutable在实际的项目开发中被严禁滥用

mutable的深入分析:

  • mutable成员变量破坏了只读对象的内部状态
  • const成员函数保证只读对象的状态不变性
  • mutable成员变量的出现无法保证状态不变性

示例1——使用mutable实现成员变量的访问统计:

#include <iostream>

using namespace std;

class Test
{
    int m_value;
    mutable int m_count;
public:
    Test(int value = 0)
    {
        m_value = value;
        m_count = 0;
    }
    
    int getValue() const
    {
        m_count++;
        
        return m_value;
    }
    
    void setValue(int value)
    {
        m_count++;
        m_value = value;
    }
    
    int getCount() const
    {
        return m_count;
    }
};

int main(int argc, char *argv[])
{
    Test t;
    
    t.setValue(100); // 满足普通对象
    
    cout << "t.m_value = " << t.getValue() << endl;
    cout << "t.m_count = " << t.getCount() << endl;
    
    const Test ct(200); // 满足只读对象
    
    cout << "ct.m_value = " << ct.getValue() << endl;
    cout << "ct.m_count = " << ct.getCount() << endl;
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
t.m_value = 100
t.m_count = 2
ct.m_value = 200
ct.m_count = 1

示例2——不使用mutable实现成员变量的访问统计:

#include <iostream>

using namespace std;

class Test
{
    int m_value;
    int * const m_pCount;
    /* mutable int m_count; */
public:
    Test(int value = 0) : m_pCount(new int(0))
    {
        m_value = value;
        /* m_count = 0; */
    }
    
    int getValue() const
    {
        /* m_count++; */
        *m_pCount = *m_pCount + 1;
        return m_value;
    }
    
    void setValue(int value)
    {
        /* m_count++; */
        *m_pCount = *m_pCount + 1;
        m_value = value;
    }
    
    int getCount() const
    {
        /* return m_count; */
        return *m_pCount;
    }
    
    ~Test()
    {
        delete m_pCount;
    }
};

int main(int argc, char *argv[])
{
    Test t;
    
    t.setValue(100); // 满足普通对象
    
    cout << "t.m_value = " << t.getValue() << endl;
    cout << "t.m_count = " << t.getCount() << endl;
    
    const Test ct(200); // 满足只读对象
    
    cout << "ct.m_value = " << ct.getValue() << endl;
    cout << "ct.m_count = " << ct.getCount() << endl;
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
t.m_value = 100
t.m_count = 2
ct.m_value = 200
ct.m_count = 1

2.new / delete

面试题: new关键字创建出来的对象位于什么地方?

被忽略的事实: new / delete的本质是C++预定义的操作符 C++对这两个操作符做了严格的行为定义:

  • new
    1. 获取足够大的内存空间默认为堆空间
    2. 在获取的空间中调用构造函数创建对象
  • delete
    1. 调用析构函数销毁对象
    2. 归还对象所占用的空间默认为堆空间

在C++中能够重载new / delete操作符:

  • 全局重载(不推荐
  • 局部重载(针对具体类进行重载

重载new / delete的意义在于改变动态对象创建时的内存分配方式

new / delete 的重载方式: C++解析(31):自定义内存管理(完) (new和delete默认就是静态成员函数,不管你写不写static。)

示例——静态存储区中创建动态对象:

#include <iostream>

using namespace std;

class Test
{
    static const unsigned int COUNT = 4;
    static char c_buffer[];
    static char c_map[];
    
    int m_value;
public:
    void* operator new (unsigned long size)
    {
        void* ret = NULL;
        
        for(int i=0; i<COUNT; i++)
        {
            if( !c_map[i] )
            {
                c_map[i] = 1;
                
                ret = c_buffer + i * sizeof(Test);
                
                cout << "succeed to allocate memory: " << ret << endl;
                
                break;
            }
        }
        
        return ret;
    }
    
    void operator delete (void* p)
    {
        if( p != NULL )
        {
            char* mem = reinterpret_cast<char*>(p);
            int index = (mem - c_buffer) / sizeof(Test);
            int flag = (mem - c_buffer) % sizeof(Test);
            
            if( (flag == 0) && (0 <= index) && (index < COUNT) )
            {
                c_map[index] = 0;
                
                cout << "succeed to free memory: " << p << endl;
            }
        }
    }
};

char Test::c_buffer[sizeof(Test) * Test::COUNT] = {0};
char Test::c_map[Test::COUNT] = {0};

int main(int argc, char *argv[])
{
    Test* pt = new Test;
    
    delete pt;
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
succeed to allocate memory: 0x601380
succeed to free memory: 0x601380

(可以看到new和delete的重载函数确实被调用了。)

示例——进一步试验:

int main(int argc, char *argv[])
{
    cout << "===== Test Single Object =====" << endl;
     
    Test* pt = new Test;
    
    delete pt;
    
    cout << "===== Test Object Array =====" << endl;
    
    Test* pa[5] = {0};
    
    for(int i=0; i<5; i++)
    {
        pa[i] = new Test;
        
        cout << "pa[" << i << "] = " << pa[i] << endl;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << "delete " << pa[i] << endl;
        
        delete pa[i];
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
===== Test Single Object =====
succeed to allocate memory: 0x6013a0
succeed to free memory: 0x6013a0
===== Test Object Array =====
succeed to allocate memory: 0x6013a0
pa[0] = 0x6013a0
succeed to allocate memory: 0x6013a4
pa[1] = 0x6013a4
succeed to allocate memory: 0x6013a8
pa[2] = 0x6013a8
succeed to allocate memory: 0x6013ac
pa[3] = 0x6013ac
pa[4] = 0
delete 0x6013a0
succeed to free memory: 0x6013a0
delete 0x6013a4
succeed to free memory: 0x6013a4
delete 0x6013a8
succeed to free memory: 0x6013a8
delete 0x6013ac
succeed to free memory: 0x6013ac
delete 0

(因为c_buffer的空间只能创建4个对象,因此for循环中的第5个对象就没有空间了,于是返回了空指针。) (可以使用这个方法加上二阶构造模式就可以将单例模式推广到多例模式!)

面试题: 如何在指定的地址上创建C++对象?

解决方案:

  • 在类中重载new / delete操作符
  • new的操作符重载函数中返回指定的地址
  • delete操作符重载中标记对应的地址可用

示例——自定义动态对象的存储空间:

#include <iostream>
#include <cstdlib>

using namespace std;

class Test
{
    static unsigned int c_count;
    static char* c_buffer;
    static char* c_map;
    
    int m_value;
public:
    static bool SetMemorySource(char* memory, unsigned int size)
    {
        bool ret = false;
        
        c_count = size / sizeof(Test);
        
        ret = (c_count && (c_map = reinterpret_cast<char*>(calloc(c_count, sizeof(char)))));
        
        if( ret )
        {
            c_buffer = memory;
        }
        else
        {
            free(c_map);
            
            c_map = NULL;
            c_buffer = NULL;
            c_count = 0;
        }
        
        return ret;
    }
    
    void* operator new (unsigned long size)
    {
        void* ret = NULL;
        
        if( c_count > 0 )
        {
            for(int i=0; i<c_count; i++)
            {
                if( !c_map[i] )
                {
                    c_map[i] = 1;
                    
                    ret = c_buffer + i * sizeof(Test);
                    
                    cout << "succeed to allocate memory: " << ret << endl;
                    
                    break;
                }
            }
        }
        else
        {
            ret = malloc(size);
        }
        
        return ret;
    }
    
    void operator delete (void* p)
    {
        if( p != NULL )
        {
            if( c_count > 0 )
            {
                char* mem = reinterpret_cast<char*>(p);
                int index = (mem - c_buffer) / sizeof(Test);
                int flag = (mem - c_buffer) % sizeof(Test);
                
                if( (flag == 0) && (0 <= index) && (index < c_count) )
                {
                    c_map[index] = 0;
                    
                    cout << "succeed to free memory: " << p << endl;
                }
            }
            else
            {
                free(p);
            }
        }
    }
};

unsigned int Test::c_count = 0;
char* Test::c_buffer = NULL;
char* Test::c_map = NULL;

int main(int argc, char *argv[])
{
    char buffer[12] = {0};
    
    Test::SetMemorySource(buffer, sizeof(buffer));
    
    cout << "===== Test Single Object =====" << endl;
     
    Test* pt = new Test;
    
    delete pt;
    
    cout << "===== Test Object Array =====" << endl;
    
    Test* pa[5] = {0};
    
    for(int i=0; i<5; i++)
    {
        pa[i] = new Test;
        
        cout << "pa[" << i << "] = " << pa[i] << endl;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << "delete " << pa[i] << endl;
        
        delete pa[i];
    }
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
===== Test Single Object =====
succeed to allocate memory: 0x7ffc6b2823d0
succeed to free memory: 0x7ffc6b2823d0
===== Test Object Array =====
succeed to allocate memory: 0x7ffc6b2823d0
pa[0] = 0x7ffc6b2823d0
succeed to allocate memory: 0x7ffc6b2823d4
pa[1] = 0x7ffc6b2823d4
succeed to allocate memory: 0x7ffc6b2823d8
pa[2] = 0x7ffc6b2823d8
pa[3] = 0
pa[4] = 0
delete 0x7ffc6b2823d0
succeed to free memory: 0x7ffc6b2823d0
delete 0x7ffc6b2823d4
succeed to free memory: 0x7ffc6b2823d4
delete 0x7ffc6b2823d8
succeed to free memory: 0x7ffc6b2823d8
delete 0
delete 0

3.new[] / delete[]

new[] / delete[]new / delete 完全不同:

  • 动态对象数组创建通过 new[] 完成
  • 动态对象数组的销毁通过 delete[] 完成
  • new[] / delete[] 能够被重载,进而改变内存管理方式

new[] / delete[] 的重载方式: C++解析(31):自定义内存管理(完)

注意事项:

  • new[]实际需要返回的内存空间可能比期望的要多
  • 对象数组占用的内存中需要保存数组信息
  • 数组信息用于确定构造函数析构函数的调用次数

示例——动态数组的内存管理:

#include <iostream>
#include <cstdlib>

using namespace std;

class Test
{
    int m_value;
public:
    Test()
    {
        m_value = 0;
    }
    
    ~Test() { }
    
    void* operator new (unsigned long size)
    {
        cout << "operator new: " << size << endl;
        
        return malloc(size);
    }
    
    void operator delete (void* p)
    {
        cout << "operator delete: " << p << endl;
        
        free(p);
    }
    
    void* operator new[] (unsigned long size)
    {
        cout << "operator new[]: " << size << endl;
        
        return malloc(size);
    }
    
    void operator delete[] (void* p)
    {
        cout << "operator delete[]: " << p << endl;
        
        free(p);
    }
};

int main(int argc, char *argv[])
{
    Test* pt = NULL;
    
    pt = new Test;
    
    delete pt;
    
    pt = new Test[5];
    
    delete[] pt;
    
    return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out 
operator new: 4
operator delete: 0x150a010
operator new[]: 28
operator delete[]: 0x150a030

4.小结

  • new / delete 的本质为操作符
  • 可以通过全局函数重载 new / delete不推荐
  • 可以针对具体的类重载 new / delete
  • new[] / delete[]new / delete 完全不同
  • new[] / delete[] 也是可以被重载的操作符
  • new[] 返回的内存空间可能比期望的要多

5.C++语言学习总结

本系列学习的是“经典”C++语言: “经典”指的是什么?

  • C++ 98/03 标准在实际工程中的常用特性
  • 大多数企业的产品开发中需要使用的C++技能

C++语言的学习需要重点在于以下几个方面

  • C语言到C++的改进有哪些?
  • 面向对象的核心是什么?
  • 操作符重载的本质是什么?
  • 模板的核心意义是什么?
  • 异常处理的使用方式是什么?
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这