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

被折叠的 条评论
为什么被折叠?



