c++ - 关于 operator new 重载和异常的问题

标签 c++ c++11 exception new-operator

为什么 code snippet输出很多“这里”?

我认为程序应该在 throw std::invalid_argument( "fool"); 被调用后终止。

#include <memory>
#include <iostream>

void* operator new(std::size_t size)
{
    std::cout << "here" << std::endl;
    throw std::invalid_argument( "fool" );   //commit out this, there would be many many ouputs
    return std::malloc(size);
}

void operator delete(void* ptr)
{
    return free(ptr);
}


int main()
{
    //std::unique_ptr<int> point2int(new int(999));

    int* rawpoint2int = new int(666);
}

最佳答案

documentation对于 std::invalid_argument 持有线索:

Because copying std::invalid_argument is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking std::string&&: it would have to copy the content anyway.

您可以看到字符串参数是设计复制的。这意味着如果您以这种方式抛出此异常,则几乎可以保证重新输入 new

您还应该知道 malloc 可以返回 nullptr 这将违反 operator new 的设计,该设计应该返回一个有效的指针或扔。

在这种情况下抛出的正常异常类型是 std::bad_alloc。我无法想象你为什么要抛出 std::invalid_argument。我想也许你在某个构造函数中遇到了这个问题,并决定测试分配本身。

从技术上讲,您可以通过将默认构造的字符串作为参数传递来解决问题:

// ... but, why would you do this?!! :(
throw std::invalid_argument(std::string());  // will not allocate

哎呀,恶心。我建议你找到一个更合适的异常来抛出(如果你真的需要一个),或者创建你自己的非分配异常。

关于c++ - 关于 operator new 重载和异常的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71402872/

相关文章:

c++ - 将 8 个位置的 int 数组转换为 char

javascript - 如何在 Promise 中捕获未捕获的异常

c++ - C++ 处理类模板及其类型的方法是什么?

c++ - 在这种情况下,基类到底是什么?

c++ - 运算符重载 + C++

C++ 字符串比较

c++ - 更新 Vector 中对象的属性

c# - 如何检查某事是 .net 异常还是自定义异常

c# - 为什么在调用 ExceptionPolicy.HandleException 时会出现 System.InvalidOperationException?

c++ - CreateCompatibleBitmap 和 CreateDIBSection(内存 DC)