当前位置:C++技术网 > 资讯 > 详析Gdiplus::GdiplusBase::operator new

详析Gdiplus::GdiplusBase::operator new

更新时间:2015-10-04 20:36:50浏览次数:1+次

生成调试版本的 Microsoft 基础类 (MFC) 应用程序使用 GDI+ 时,您可能会收到类似于以下内容的错误消息:
错误 C2660: 新 Gdiplus::GdiplusBase::operator: 函数不带三个参数
在调试版本中,MFC 定义预处理器扩展到宏, new运算符重载新运算符带有两个额外参数。额外的参数是源的文件名和代码行号。MFC 可使用此信息在调试模式下时程序员向报告内存泄漏。此操作适用于 MFC 类因为 MFC 提供的新接受额外的参数的重载。
但是,这一业务扩展通过预处理器来完成的因为它会影响所有使用新的运算符。如果在项目中使用了任何非 MFC 类,其new运算符也会扩展,即使没有合适的新重载可用于该类。这是在 GDI+ 中,会发生什么情况,结果是,您会收到一个编译时错误消息。
若要变通解决此问题,请选择下列方法之一:

关闭预处理器扩展通过注释掉下面的源代码文件中的代码行:


#ifdef _DEBUG
#define new DEBUG_NEW
#endif
注意: 此方法具有未使用的缺点在 MFC 中的功能,帮助您跟踪内存分配和泄漏。
GDI+ 使用重载为提供新和删除运算符通过编写一些代码来接受并放弃其他的参数。可以将下面的代码演示了此方法,粘贴到新的头文件并包括新的头文件,而不是 Gdiplus.h 文件。
//// Ensure that GdiPlus header files work properly with MFC DEBUG_NEW and STL header files.

#define iterator _iterator

#ifdef _DEBUG

namespace Gdiplus
{
	namespace DllExports
	{
		#include <GdiplusMem.h>
	};

	#ifndef _GDIPLUSBASE_H
	#define _GDIPLUSBASE_H
	class GdiplusBase
	{
		public:
			void (operator delete)(void* in_pVoid)
			{
				DllExports::GdipFree(in_pVoid);
			}

			void* (operator new)(size_t in_size)
			{
				return DllExports::GdipAlloc(in_size);
			}

			void (operator delete[])(void* in_pVoid)
			{
				DllExports::GdipFree(in_pVoid);
			}

			void* (operator new[])(size_t in_size)
			{
				return DllExports::GdipAlloc(in_size);
			}

			void * (operator new)(size_t nSize, LPCSTR lpszFileName, int nLine)
			{
				return DllExports::GdipAlloc(nSize);
			}

			void operator delete(void* p, LPCSTR lpszFileName, int nLine)
			{
				DllExports::GdipFree(p);
			}

		};
	#endif // #ifndef _GDIPLUSBASE_H
}
#endif // #ifdef _DEBUG

#include <gdiplus.h>
#undef iterator
//// Ensure that Gdiplus.lib is linked.
#pragma comment(lib, "gdiplus.lib")