'declaration' : 找不到相符的運算符刪除;如果初始化擲回例外狀況,記憶體將不會釋出
備註
新的放置是用於沒有放置刪除的位置。
為具有運算符 new的物件配置記憶體時,會呼叫 物件的建構函式。 如果建構函式擲回例外狀況,則應該取消配置給物件的任何記憶體。 除非運算子函式存在符合 運算子 的運算子deletenew函式,否則無法進行。
如果您使用不含任何額外自變數的運算符new,並使用 /GX、/EHs 或 /EHa 選項編譯以啟用例外狀況處理,則編譯程式會在建構函式擲回例外狀況時產生呼叫運算符delete的程序代碼。
如果您使用運算子的new放置形式(除了配置大小之外還有自變數的表單),而且物件的建構函式擲回例外狀況,編譯程式仍會產生呼叫運算子delete的程式代碼;但如果運算符的位置形式符合配置記憶體的運算元delete放置形式new,則它只會執行此動作。
Example
例如:
// C4291.cpp
// compile with: /EHsc /W1
#include <malloc.h>
class CList
{
public:
CList(int)
{
throw "Fail!";
}
};
void* operator new(size_t size, char* pszFilename, int nLine)
{
return malloc(size);
}
int main(void)
{
try
{
// This will call ::operator new(unsigned int) to allocate heap
// memory. Heap memory pointed to by pList1 will automatically be
// deallocated by a call to ::operator delete(void*) when
// CList::CList(int) throws an exception.
CList* pList1 = new CList(10);
}
catch (...)
{
}
try
{
// This will call the overloaded ::operator new(size_t, char*, int)
// to allocate heap memory. When CList::CList(int) throws an
// exception, ::operator delete(void*, char*, int) should be called
// to deallocate the memory pointed to by pList2. Since
// ::operator delete(void*, char*, int) has not been implemented,
// memory will be leaked when the deallocation cannot occur.
CList* pList2 = new(__FILE__, __LINE__) CList(20); // C4291
}
catch (...)
{
}
}
上述範例會產生警告 C4291,因為尚未定義符合運算子放置格式的運算子deletenew放置形式。 若要解決此問題,請在main上方插入下列程式代碼。 請注意,除了第一個參數之外,所有多載運算符 delete 函式參數都符合多載運算符 new的函式參數。
void operator delete(void* pMem, char* pszFilename, int nLine)
{
free(pMem);
}