如何在 C++ 中使用自定义消息抛出 std::bad_alloc?

ale*_*555 3 c++ bad-alloc

由于 VS2008 类 bad_alloc 不提供带有字符串参数的构造函数。有没有可能在不覆盖这样的类的情况下创建自定义消息?

// this is only pseudo-code
class custom_exception : bad_alloc {
public:
    string Message;
    custom_exception(string m) {Message = m;}
}
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 5

bad_alloc需要在不分配内存的情况下进行构造,这就是为什么它的构造函数不接受消息参数的原因。您当然可以将其子类化并覆盖what.