gdiplus exception
<span style="font-size:14px;">#include <windows.h> #include <gdiplus.h> #include <stdio.h> using namespace Gdiplus; #pragma comment(lib, "gdiplus.lib") int main() { GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); printf("%d\n", gdiplusStartupInput.GdiplusVersion); Image image(L"ing.png"); printf("The width of the image is %u.\n", image.GetWidth()); printf("The height of the image is %u.\n", image.GetHeight()); GdiplusShutdown(gdiplusToken); return 0; } </span>
一个使用Gdiplus的Hello World程序,居然都出现了错误。输出居然没有问题=)。
因为这学期到下学期打算深入学习调试技术,一心想着不丢弃所遇到的任何一个bug。
F5跟踪一下:
在Image类的析构函数中出现一个Access violation 错误。
析构函数一般都是用来释放空间的,为什么会出错呢?
自认为很重要的一点:在main函数return语句没执行之前调用的Image类的析构函数。
回想下看MSDN GdiplusStartup、GdiplusShutdown里的一句话:
RemarksYou must call GdiplusStartup before you create any GDI+ objects, and you must delete all of your GDI+ objects (or have them go out of scope) before you call GdiplusShutdown. |
解决办法:
<span style="font-size:14px;">#include <windows.h> #include <gdiplus.h> #include <stdio.h> using namespace Gdiplus; #pragma comment(lib, "gdiplus.lib") int main() { GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); { Image image(L"ing.png"); printf("The width of the image is %u.\n", image.GetWidth()); printf("The height of the image is %u.\n", image.GetHeight()); } GdiplusShutdown(gdiplusToken); return 0; } </span>把gdi+处理函数放在一个{}内
或者
<span style="font-size:14px;">#include <windows.h> #include <gdiplus.h> #include <stdio.h> using namespace Gdiplus; INT main() { GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Image *image = new Image(L"ing.png"); printf("The width of the image is %u.\n", image->GetWidth()); printf("The height of the image is %u.\n", image->GetHeight()); delete image; GdiplusShutdown(gdiplusToken); return 0; } </span>
Keep it simple!