Naw*_*waz 3 c# c++ memory-management dynamic-memory-allocation
在C++中,我们通常会看到和编写代码,
Sample sample=new Sample();
if ( sample == NULL )
{
std::cout<<"Memory allocation failed" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但是在C#中,我很少看到这个:(至少我从未见过这个)
Sample sample = new Sample();
if ( sample == null )
{
Console.WriteLine("Memory allocation failed\n");
}
Run Code Online (Sandbox Code Playgroud)
意思是,在C#中,我们很少检查是否new失败.为什么会这样?它与"在C#中,新的永不失败"有关吗?在C#中有这样的东西new永远不会失败吗?
如果它失败了,为什么这样的"检查"在C#中如此罕见?我不是在谈论OutOfMemoryException,这毕竟是例外,而不是"检查".我在谈论编码风格.
Umm*_*mma 14
根据msdn
如果new运算符无法分配内存,则会抛出异常OutOfMemoryException.
http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx
顺便说一句,只有旧的C++编译器在尝试分配内存时返回0.现代的抛出std :: bad_alloc异常.如果你希望旧的行为,你需要写
Sample sample=new(std::nothrow) Sample();
Run Code Online (Sandbox Code Playgroud)
bdo*_*lan 12
在C#中,如果失败则new抛出一个OutOfMemoryException,因此NULL不需要检查.
顺便提一下,同样适用于C++ - 如果失败则new抛出std::bad_alloc,所以实际上也没有必要NULL在C++中进行测试.
在C++中,不像malloc,失败时new不返回NULL.实际上,它会std::bad_alloc在失败时抛出异常.
如果要在失败时new返回NULL,则必须明确告诉它不要抛出异常.使用std::nothrow版本用于此目的.(头文件:<new>)
如果new失败,那么就会OutOfMemoryException抛出.
所以你所拥有的C++代码就相当于:
try {
Sample sample = new Sample();
} catch(OutOfMemoryException e) {
Console.WriteLine("Memory allocation failed\n");
}
Run Code Online (Sandbox Code Playgroud)
Sample sample=new Sample();
if ( sample == NULL )
{
// You will never get here!
std::cout<<"Memory allocation failed" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我们也不用C++编写."Memory allocation failed"永远不会出现.如果分配失败,在两种语言中都会出现异常.在C++中,它是std::bad_alloc在C#中的OutOfMemoryException.
| 归档时间: |
|
| 查看次数: |
3122 次 |
| 最近记录: |