首页
学习
活动
专区
圈层
工具
发布

C++内存分配失败的那些事儿

对于内存分配失败,C++提供了两种常见的处理方式:抛出异常(std::bad_alloc)和返回空指针。如何选择合适的处理机制,取决于应用程序的需求以及对错误的容忍度。...默认情况下,new会在内存分配失败时抛出std::bad_alloc异常。...例如: int* ptr = new int[100]; //如果分配失败,将抛出std::bad_alloc异常 这使得程序在遇到内存分配失败时能够及时发现并处理错误。...std::bad_alloc是std::exception的派生类,表示内存分配失败的错误。 3.返回空指针 在某些情况下,程序员可能不希望因为内存分配失败而中断程序的执行。...抛出std::bad_alloc异常适用于那些对内存分配失败容忍度较低的程序,而返回空指针则适用于那些希望程序继续执行的场景。

1.1K10
  • 您找到你想要的搜索结果了吗?
    是的
    没有找到

    【C++特殊工具与技术】优化内存分配(三):operator new函数和opertor delete函数

    以下是最核心的 4 种形式(以 64 位系统为例): ①普通内存分配(抛出异常) // 分配size字节的原始内存,失败时抛出std::bad_alloc异常 void* operator new(std...delete调用free 异常行为 普通版本分配失败抛std::bad_alloc,nothrow 版本返回nullptr 内存对齐 普通版本保证至少alignof(std::max_align_t)...ptr) throw std::bad_alloc{}; return ptr; } // 重载全局operator delete(普通版本) void operator delete(void...ptr) throw std::bad_alloc{}; std::lock_guardstd::mutex> lock(mtx); allocatedMemory[ptr] = size...ptr) throw std::bad_alloc{}; return ptr; } // 重载对齐版本的operator delete(C++17) void operator delete

    11710
    领券