C++ 类的静态成员变量指针如何释放

类的静态成员变量指针,如何释放?

目前有两种方法:

  1. 智能指针
  2. 使用静态变量维护一个引用计数,每创建一个对象,引用计数加1,析构函数中,引用计数减一,直到为0才释放内存
//方法一:使用智能指针
//使用智能指针在程序结束时(main大括号之外)会弹出结束对话框,使用普通指针不会弹出
#include <iostream>
#include <memory>
#include <Windows.h>
using namespace std;

class A
{
public:
    A()
    {
        MessageBox(GetForegroundWindow(), "", "【创建】", 1);
    }

    ~A()
    {
        cout << "delete" << endl;
        MessageBox(GetForegroundWindow(), "", "【结束】", 1);
    }
};

class B 
{
public:
    B() 
    {

    };

    ~B()
    {

    };

private:
    static std::shared_ptr<A> m_instance;
    //static A* m_instance;
};

std::shared_ptr<A> B::m_instance = std::shared_ptr<A>(new A());
//A* B::m_instance = new A();


int main()
{
    B b;
    B b1;
    B b2;
    B b3;

    return 0;
}
//方法二:参考链接:https://blog.csdn.net/vgxpm/article/details/47048873
//使用静态变量维护一个引用计数,每创建一个对象,引用计数加1,
//析构函数中,引用计数减一,直到为0才释放内存
#include<iostream>
using namespace std;

class A
{
public:
    A()
    {
        cout << "create" << endl;
    }

    ~A()
    {
        cout << "delete" << endl;
    }
};

class B 
{
public:
    B() 
    {
        if (m_instance == NULL)
        {
            m_instance = new A();
        }

        ++m_count;
        cout << m_count << endl;
    };

    ~B()
    {
        --m_count;
        cout << m_count << endl;

        if (m_instance != NULL && m_count == 0)
        {
            delete m_instance;
            m_instance = NULL;
        }
    };

private:
    static A* m_instance;
    static int m_count;
};

A* B::m_instance = new A();
int B::m_count = 0;

int main()
{
    B b;
    B b1;
    B b2;
    B b3;

    return 0;
}

   

  • 12
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值