Exception 在分配超出限制的对象时,Clang无法抛出std::bad_alloc

Exception 在分配超出限制的对象时,Clang无法抛出std::bad_alloc,exception,memory-management,c++11,clang,Exception,Memory Management,C++11,Clang,当我试图分配一个超出其限制的对象时,我很难理解clang是如何抛出异常的。例如,如果我编译并运行以下代码: #include <limits> #include <new> #include <iostream> int main(int argc, char** argv) { typedef unsigned char byte; byte*gb; try{ gb=new byte[std::numeric_lim

当我试图分配一个超出其限制的对象时,我很难理解clang是如何抛出异常的。例如,如果我编译并运行以下代码:

#include <limits>
#include <new>
#include <iostream>

int main(int argc, char** argv) {
    typedef unsigned char byte;
    byte*gb;
    try{
        gb=new byte[std::numeric_limits<std::size_t>::max()];
    }
    catch(const std::bad_alloc&){
        std::cout<<"Normal"<<std::endl;
        return 0;}
    delete[]gb;
    std::cout<<"Abnormal"<<std::endl;
    return 1;
}
#包括
#包括
#包括
int main(int argc,字符**argv){
typedef无符号字符字节;
字节*gb;
试一试{
gb=新字节[std::numeric_limits::max()];
}
捕获(const std::bad_alloc&){

std::cout由于数组未使用,似乎clang消除了分配:

#include <limits>
#include <new>
#include <iostream>

int main(int argc, char** argv)
{
    typedef unsigned char byte;
    bytes* gb;
    const size_t max = std::numeric_limits<std::size_t>::max();
    try
    {
        gb = new bytes[max];
    }
    catch(const std::bad_alloc&)
    {
        std::cout << "Normal" << std::endl;
        return 0;
    }
    try
    {
        gb[0] = 1;
        gb[max - 1] = 1;
        std::cout << gb[0] << gb[max - 1] << "\n";
    }
    catch ( ... )
    {
        std::cout << "Exception on access\n";
    }
    delete [] gb;
    std::cout << "Abnormal" << std::endl;
    return 1;
}
#包括
#包括
#包括
int main(int argc,字符**argv)
{
typedef无符号字符字节;
字节*gb;
const size_t max=std::numeric_limits::max();
尝试
{
gb=新字节[max];
}
捕获(const std::bad_alloc&)
{

看起来MacOSX上的clang++确实抛出了bad_alloc,但它也从malloc打印了一条错误消息

节目:

// bad_alloc example
#include <iostream>     // std::cout
#include <sstream>
#include <new>          // std::bad_alloc

int main(int argc, char *argv[])
{
  unsigned long long memSize = 10000;
    if (argc < 2)
        memSize = 10000;
    else {
        std::istringstream is(argv[1]); // C++ atoi
        is >> memSize;
    }
  try
  {
    int* myarray= new int[memSize];
    std::cout << "alloc of " << memSize << " succeeded" << std::endl;
  }
  catch (std::bad_alloc& ba)
  {
    std::cerr << "bad_alloc caught: " << ba.what() << '\n';
  }
  std::cerr << "Program exiting normally" << std::endl;
  return 0;
}
我还在Windows 7上使用g++尝试了相同的程序: C:\Users\David\Dropbox\Projects\Miscellaneous>g++-o badallocw badalloc.cpp

C:\Users\David\Dropbox\Projects\Miscellaneous>badallocw
alloc of 10000 succeeded

C:\Users\David\Dropbox\Projects\Miscellaneous>badallocw 1234567890
bad_alloc caught: std::bad_alloc
注:该程序是示例的修改版本


libc++实现:我想更聪明的优化器甚至会优化这段代码……你说得非常对。谢谢。。。
C:\Users\David\Dropbox\Projects\Miscellaneous>badallocw
alloc of 10000 succeeded

C:\Users\David\Dropbox\Projects\Miscellaneous>badallocw 1234567890
bad_alloc caught: std::bad_alloc