各位大侠,请看下面的语句:
char *p = NULL;
try
{
p = new char[10];
if (p == NULL)
return;
}
catch(...)
{
if (p != NULL)
delete p;
return;
} 我想问一下,new时如果发生问题,p的值是保持NULL,还是变为vc默认的0xcdcdcdcd ?
因为如果变为0xcdcdcdcd,那我在catch中就会发生delete p的错误,而导致程序出问题了。
这是我商业程序中的问题,请一定非常清醒再回答,不太清楚的人万勿回答,谢谢。
char *p = NULL;
try
{
p = new char[10];
if (p == NULL)
return;
}
catch(...)
{
if (p != NULL)
delete p;
return;
} 我想问一下,new时如果发生问题,p的值是保持NULL,还是变为vc默认的0xcdcdcdcd ?
因为如果变为0xcdcdcdcd,那我在catch中就会发生delete p的错误,而导致程序出问题了。
这是我商业程序中的问题,请一定非常清醒再回答,不太清楚的人万勿回答,谢谢。
不知道new是不是返回NULL,那么你就首先应该想到去MSDN查帮助,然后是通过网站搜索相关主题,看别人是怎么解决的。
请一定非常清醒再回答,不太清楚的人万勿回答--不要这么样说话,听了不舒服。
看你这个问题前,我也不知道是不是返回NULL。因此查MSDN。对new operator的说明中有这么一段:
If there is insufficient memory for the allocation request, by default operator new returns NULL.
也许对你有帮助。
但我没有实验,所以我不正面回答了。
/* HANDLER.CPP: This program uses _set_new_handler to
* print an error message if the new operator fails.
*/#include <stdio.h>
#include <new.h>/* Allocate memory in chunks of size MemBlock. */
const size_t MemBlock = 1024;/* Allocate a memory block for the printf function to use in case
* of memory allocation failure; the printf function uses malloc.
* The failsafe memory block must be visible globally because the
* handle_program_memory_depletion function can take one
* argument only.
*/
char * failsafe = new char[128];/* Declare a customized function to handle memory-allocation failure.
* Pass this function as an argument to _set_new_handler.
*/
int handle_program_memory_depletion( size_t );void main( void )
{
// Register existence of a new memory handler.
_set_new_handler( handle_program_memory_depletion );
size_t *pmemdump = new size_t[MemBlock];
for( ; pmemdump != 0; pmemdump = new size_t[MemBlock] );
}int handle_program_memory_depletion( size_t size )
{
// Release character buffer memory.
delete failsafe;
printf( "Allocation failed, " );
printf( "%u bytes not available.\n", size );
// Tell new to stop allocation attempts.
return 0;
}
程序呼叫terminate()結束執行.除非你一開始char *p = NULL; 改為 char *p; p的此時值才是compiler給的0xcdcdcdcd,
所以丟出例外才是0xcdcdcdcd,若以你的例子是NULL.以 dynamic_cast 為例:1. 當以pointer轉型時,失敗是回傳null,不丟出例外(記的開啟rtti)
2. 當以reference 轉型時,失敗是丟出例外(記的開啟rtti)ex:
#include<iostream>
#include <exception>
using namespace std;
class A
{
public:
virtual void abc(){}
};
class B:public A
{
};
int main()
{ A AA;
try
{
B& BB=dynamic_cast<B&>(AA); //故意不當轉型,丟出例外
printf("TEST"); //當上面丟出例外,直接跳過此行,也表示了BB 事實上referennce
//所給的預設值0xcccccccc
}
catch(exception & ex)
{
cout<<ex.what();//顯示 Bad dynamic_cast!
// 當執行到此,為了再次確定,去查看BB 的位址,仍然還是0xcccccccc.
}
}
我现在是debug版。
我很奇怪的是,有的线程和其他的线程一点关系也没有,为什么也会停下来。是不是VC一个线程出问题,其他的线程也会停下来呢?