我不确定我的自定义异常方法是否正确。我想要做的是自定义消息抛出异常,但似乎我创建了一个内存泄漏...带消息的C++异常
class LoadException: public std::exception {
private:
const char* message;
public:
LoadException(const std::string message);
virtual const char* what() const throw();
};
LoadException::LoadException(const std::string message) {
char* characters = new char[message.size() + 1];
std::copy(message.begin(), message.end(), characters);
characters[message.size()] = '\0';
this->message = characters;
}
我用它如下:
void array_type_guard(Local<Value> obj, const std::string path) {
if (!obj->IsArray()) {
throw LoadException(path + " is not an array");
}
}
try {
objects = load_objects();
} catch (std::exception& e) {
ThrowException(Exception::TypeError(String::New(e.what())));
return scope.Close(Undefined());
}
我怕阵列创建在构造函数中永远不会被删除。但我不知道如何删除它 - 我应该添加析构函数还是使用完全不同的方法?
更新:
我其实是试图用串类,如下所示:
class LoadException: public std::exception {
private:
const char* msg;
public:
LoadException(const std::string message);
virtual const char* what() const throw();
};
LoadException::LoadException(const std::string message) {
msg = message.c_str();
}
const char* LoadException::what() const throw() {
return msg;
}
但无法获得错误信息,那么 - 当我打印的“显示一些随机输出什么()”。
只需使用'string'来存储消息。或者是否有'char *'的原因? –
不,没有char *的理由。我将代码更改为字符串。谢谢。 –
或者只是用一个析构函数来删除分配的字符数组。 –