[C/C++]_[初级]_[关于Gdiplus::Bitmap使用的注意事项]

本文探讨了在使用 GDI+ 的 Bitmap 类时常见的错误及其原因。特别关注于避免在 Gdiplus::GdiplusShutdown 后删除 Bitmap 指针所导致的崩溃问题,并通过示例代码展示了正确的资源管理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景

1.我们一般使用 Gdiplus::Bitmap 来存储图像数据, 使用shared_ptr来对 Gdiplus::Bitmap 进行封装, 达到使用引用计数共享图像对象, 减少内存占用的目的.

2.偶尔的时候如果 Gdiplus::Bitmap 使用不当释放时会出现崩溃错误, 什么原因呢?

说明

1.原因是 Gdiplus::Bitmap* 不可以在 Gdiplus::GdiplusShutdown 调用后再 delete, 不然会崩溃.

2.崩溃位置, 可见在调用delete bitmap对象时崩溃.


private:
    virtual void _Destroy()
        {   // destroy managed resource
        delete _Ptr;
        }

这里写图片描述

例子


// test-gdiplus.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <GdiPlus.h>
#include <vector>
#include <memory>

std::vector<std::shared_ptr<Gdiplus::Bitmap>> gImages;


int _tmain(int argc, _TCHAR* argv[])
{
    ULONG_PTR m_gdiplusToken;
    Gdiplus::GdiplusStartupInput  m_gdiplusStartupInput;
    Gdiplus::GdiplusStartup(&m_gdiplusToken,&m_gdiplusStartupInput,NULL);

    // 创建 Bitmap
    auto bitmap = new Gdiplus::Bitmap(200,200);
    gImages.push_back(std::shared_ptr<Gdiplus::Bitmap>(bitmap));

    Gdiplus::GdiplusShutdown(m_gdiplusToken);

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peter(阿斯拉达)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值