如果 new 运算符未能分配内存,则只有当我在 new 语句周围放置一个 try-catch 块时,才会捕获异常 std::bad_alloc 。如果我在下面几个堆栈帧的调用者中有 try-catch 块,它不会在那里被捕获,并且我会遇到异常的程序终止。为什么会这样?这是在 Microsoft Visual Studio 2008 上。
编辑:好的,这是不工作的代码。下面的函数是我调用新函数的地方,下面的函数是它下面的堆栈帧。最后一个函数是我有 catch 子句的地方,但它没有在那里被捕获。
void HTTPResponseBuff::grow()
{
if (m_nMaxSize > m_nStartConstGrowSize)
m_nMaxSize += m_nConstGrowSize;
else
m_nMaxSize = 2 * m_nMaxSize;
char* pTmp = new char[m_nMaxSize];
. . .
}
void HTTPResponseBuff::write(const char* pBuf, size_t len)
{
char* pCh;
while (getRemainingCapacity(pCh) < len)
grow();
. . .
}
size_t HTTPTransport::responseCallback(void *pRespData, size_t size,
size_t nmemb, void *pRespBuff)
{
const char* pChar = (const char*)pRespData;
register int respDataLen = size * nmemb;
((HTTPResponseBuff*)pRespBuff)->write(pChar, respDataLen);
return respDataLen;
}
A few curl library stackframes here. These are C code, not C++.
ISTATUS HTTPTransport::invoke()
{
invokeCleanup();
//make the HTTP call
CURLcode retCode;
try{
retCode = curl_easy_perform(m_pCurl);
}
catch(std::bad_alloc& ba)
{
strcpy(m_pErrMsg,ba.what());
m_status = IFAILURE;
}
}
此外,我捕获 bad_alloc 时的堆栈帧(在新语句周围的 catch 子句中)在这里:http ://s289.photobucket.com/albums/ll211/spiderman2_photo_bucket/?action=view¤t=bad_alloc.jpg