#include <exception>
#include <iostream>
#include <cstdio>
using namespace std;
class BaseException : exception {
public:
BaseException(const char* message) : message(message) {}
const char* getMessage() {
return message;
}
private:
const char* message;
};
void wrong() {
unsigned short int argumentCallCounter = 1;
/// @todo check why commented below does not work ?!
// char tmp[13 + sizeof(argumentCallCounter)];
/// @todo but this works
char* tmp = new char[13 + sizeof(argumentCallCounter)];
sprintf(tmp, "No %u argument", argumentCallCounter);
throw BaseException(tmp);
}
int main(int argc, char** argv) {
try {
wrong();
} catch (BaseException e) {
cout << e.getMessage() << endl;
}
return 0;
}
上面的代码有效,但是在注释中,有一段代码不起作用。
char tmp[13 + sizeof(argumentCallCounter)];
我知道它不起作用,因为当程序离开函数 错误
时,变量 tmp 不再存在。
有人可以帮忙吗?
还有我写的那个决定:
char* tmp = new char[13 + sizeof(argumentCallCounter)];
这也不好,因为当程序完成时,内存泄漏,因为没有人删除 tmp
最佳答案
我通常抛出一个用 std::string 初始化的 std::runtime_exception。
关于C++ 变量不再存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659738/