C++语言学习(二十)——自定义内存管理

news/2024/7/7 16:24:50

C++语言学习(二十)——自定义内存管理

一、统计类对象中成员变量的访问次数

mutable是为了突破const函数的限制而设计的,mutable修饰的成员变量将永远处于可改变的状态。mutable成员变量破坏了只读对象的内部状态,而const成员函数保证只读对象的状态不变性,因此mutable成员变量无法保证只读对象状态的不变性。

#include <iostream>

using namespace std;

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

int main(int argc, char *argv[])
{
    Test test1;
    test1.setValue(100);
    cout << test1.getCount() << endl;

    const Test test2;
    test2.getValue();
    cout << test2.getCount() << endl;
    return 0;
}

上述代码使用mutable修饰成员变量m_count,确保在const函数内部也可以改变其值,但mutable破坏了只读对象状态的不变性,所以不推荐。

#include <iostream>

using namespace std;

class Test
{
public:
    Test():m_count(new int(0))
    {
    }
    void setValue(const int value)
    {
        *m_count = *m_count + 1;
        m_data = value;
    }
    int getValue()
    {
        *m_count = *m_count + 1;
        return m_data;
    }
    int getValue()const
    {
        *m_count = *m_count + 1;
        return m_data;
    }
    int getCount()const
    {
        return *m_count;
    }
private:
    int m_data;
    int*  const m_count;
};

int main(int argc, char *argv[])
{
    Test test1;
    test1.setValue(100);
    cout << test1.getCount() << endl;

    const Test test2;
    test2.getValue();
    cout << test2.getCount() << endl;
    return 0;
}

上述代码使用指针常量统计访问成员变量的次数,不会破坏只读对象的状态不变性。

二、new/delete操作符重载

1、new/delete操作符本质

new/delete的本质是C++预定义的操作符,C++语言规范对new/delete操作符做出了严格的规范:
A、new关键字用于获取足够的内存空间(默认为堆空间),在获取的空间中调用构造函数创建对象。
B、delete调用析构函数销毁对象,归还对象所占用的空间(默认为堆空间)。
C++语言中可以重载new/delete操作符,重载new/delete操作符的意义在于改变动态对象创建时的内存分配方式,可以将new创建的对象分配在栈空间、静态存储空间、指定地址空间。
new/delete操作符支持全局重载、局部重载,但不推荐对new/delete操作符进行全局重载,通常对new/delete操作符进行局部重载,如针对具体的类进行new/delete操作符重载。
new/delete操作符重载函数默认为静态函数,无论是否显示声明static关键字。

    //static member function
    void* operator new(unsigned int size)
    {
        void* ret = NULL;
        /* ret point to allocated memory */
        return ret;
    }
    //static member function
    void operator delete(void* p)
    {
        /* free the memory which is pointed by p */
    }

2、在静态存储区创建对象

#include <iostream>

using namespace std;

class Test
{
private:
    static const unsigned int COUNT = 4;
    static char c_buffer[];
    static char c_map[];
    int m_value;
public:
    Test(int value = 0)
    {
        m_value = value;
        cout << "value : " << value << endl;
    }
    //static member function
    void* operator new (unsigned int 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;
    }
    //static member function
    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;
            }
        }
    }
    int getValue()const
    {
        return m_value;
    }
};

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

int main(int argc, char *argv[])
{
    cout << "===== Test Single Object =====" << endl;
    Test* pt = new Test(1);
    delete pt;

    cout << "===== Test Object Array =====" << endl;
    Test* pa[5] = {0};
    for(int i=0; i<5; i++)
    {
        pa[i] = new Test(100 + i);
        cout << "pa[" << i << "] = " << pa[i] << endl;
    }
    for(int i=0; i<5; i++)
    {
        cout << "delete " << pa[i] << endl;
        if(pa[i] != NULL)
        {
            delete pa[i];
        }
    }

    return 0;
}

上述代码,new会创建Test对象到静态存储空间中,从打印结果可以知道new创建Test对象时先调用new操作符重载函数,在返回的空间中再调用Test构造函数。

3、在指定地址创建对象

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

#include <iostream>
#include <string>
#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 int 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;
}

上述代码中,可以在指定地址空间创建对象,也可以不指定地址空间,此时在堆空间创建对象。

4、在栈空间创建对象

#include <iostream>

using namespace std;

class Test
{
    int m_value;
public:
    Test(int value = 0)
    {
        m_value = value;
        cout << "value : " << m_value << endl;
        cout << "this : " << this << endl;
    }
};

int main(int argc, char *argv[])
{
    Test test(100);
    //在栈空间创建对象
    Test* pTest = new(&test) Test(1000);

    return 0;
}
上述代码中,可以使用new操作符的默认实现在栈空间创建对象。

5、new[]/delete[]关键字

new[]/delete[]关键字与new/delete关键字完全不同,是一组全新的关键字。
new[]关键字用于创建动态对象数组,delete[]关键字用于销毁动态对象数组。new[]/delete[]关键字可以进行重载,用于优化内存管理方式。new[]关键字返回的空间大小通常大于预期的动态数组空间大小。

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Test
{
    int m_value;
public:
    Test(int value = 0)
    {
        m_value = value;
    }

    ~Test()
    {
    }

    void* operator new (unsigned int 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 int 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;
}

上述代码中,重载了new[]/delete[]关键字。

转载于:https://blog.51cto.com/9291927/2165138


http://www.niftyadmin.cn/n/4151235.html

相关文章

python 两个列表相互映射_自学python,必须要懂得四种数据结构,看完快速掌握...

01、数据结构是相互之间存在一种或多种特定关系的数据元素的集合今天要讲python的四个内置数据结构&#xff1a;分别是列表、元组、集合和字典&#xff0c;每种结构数据都有自己的特点&#xff0c;应用于不同情况1、(list)列表中的元素是有序的&#xff0c;元素内容可以修改。列…

mysql如何处理亿级数据的SQL 注意事项

2019独角兽企业重金招聘Python工程师标准>>> 1、应尽量避免在 where 子句中使用!或<>操作符&#xff0c;否则将引擎放弃使用索引而进行全表扫描。 2、对查询进行优化&#xff0c;应尽量避免全表扫描&#xff0c;首先应考虑在 where 及 order by 涉及的列上建立…

lua 如何获取当前星期的周六_lua学习前5章解惑

lua学习前5章解惑基础概念-l 参数-- a&#xff0c;b文件均需放到 lua.exe 所在的文件目录 -- a.lua 文件 x 5 -- b.lua 文件 print(x) -- 交互模式中输入 lua -la -lb -- 先运行 a.lua &#xff0c;再运行 b.lua -- 结果为 5表达式链表list nil local rows 1 list_next ni…

前端基础10:匿名函数

function 函数类型的作用&#xff1a;- 1.具有封装性&#xff08;防止冲突和覆盖&#xff09; - 2.减少冗余代码&#xff0c;把实现相同功能的代码都写在一个函数里&#xff0c;等下次需要实现这个功能时&#xff0c;只需要执行这个函数即可 复制代码 函数的定义:function 函数…

javascript 设计模式_开发人员都应该了解的 7 种 JavaScript 设计模式

开发人员将 JavaScript 设计模式作为解决问题的模板是很合适的&#xff0c;但并不是说这些模式可以代替开发人员的工作。通过设计模式&#xff0c;我们可以将许多开发人员的经验结合起来&#xff0c;以优化过的方式来构造代码&#xff0c;从而解决我们所面对的问题。设计模式还…

使用Mikado进行基因结构注释

Mikado是基于Python3写的基因组结构注释工具&#xff0c;它主要做的是从多个转录组组装工具得到的转录本里挑选出最好的结果作为基因组的结构注释。此外&#xff0c;它还会基于同源蛋白比对结果对转录本打分。换句话说这个软件主要是根据转录组数据进行注释&#xff0c;没有 ab…

建设方案 移动网上政务办公_网上订单系统如何让经销商实现移动化办公管理...

随着零售行业的不断发展以及互联网的不断渗入&#xff0c;人民的生活水平也在逐步的提升&#xff0c;消费观念发生了巨大的改变&#xff0c;从现金到手机支付这一过程&#xff0c;就可以看到时代在进步&#xff0c;我们要拥抱互联网&#xff0c;抛弃旧的观念&#xff0c;实现质…

python中控制结构_Python基础-一般控制结构

本文为《爬着学Python》系列第七篇文章。我们拖了好久&#xff0c;终于要开始真正进行Python语法的讲解了。是的&#xff0c;变量与对象只是Python的语义特征&#xff0c;编程语言的语法特征体现在控制结构。也就是我们一般说的if&#xff0c;while。我们今天要讲的主要就是这两…