关于类静态成员变量指针通过动态分配的内存如何回收的探讨

一个类假如存在一个静态成员变量指针,在以下几种情况下动态分配内存,该如何回收内存:

1)在外部函数中动态分配内存,代码如下:

test.cpp

class Test
{
public:
    static char* m_pSZ;
};

char* Test::m_pSZ = NULL;

void testAlloc()
{
    Test::m_pSZ = new char[16];
}

int main()
{
    testAlloc();
    
    
    std::cout << "Already alloc for Test::m_pSZ!" << std::endl;

    return 0;
}

通过使用g++ -g test.cpp -c test编译,再g++ -o test test.o链接成执行文件,最后通过检测内存泄漏工具valgrind检测,命令如下:

valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./test

检测结果如下:

==14924== Memcheck, a memory error detector
==14924== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==14924== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==14924== Command: ./test
==14924== 
Already alloc for Test::m_pSZ!
==14924== 
==14924== HEAP SUMMARY:
==14924==     in use at exit: 16 bytes in 1 blocks
==14924==   total heap usage: 1 allocs, 0 frees, 16 bytes allocated
==14924== 
==14924== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==14924==    at 0x402ACDB: operator new[](unsigned int) (vg_replace_malloc.c:383)
==14924==    by 0x80486EE: testAlloc() (test.cpp:13)
==14924

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值