我一直在读书,我不应该扔std::string
或一些其他类分配内存。 像这里或更重要的是这里的第3点- 不要嵌入std::string
对象 。
所以现在我想插入的boost ::例外,我的项目,我看到了什么: 很多字符串 。
为什么不提高履行自己的建议?
如果我有不能被硬编码,像萨法德在配置文件中的参数,我怎样才能把它们变成一个例外,在不使用std::string
?
或者是指引不使用std::string
只有确实使用std::string
尽可能少准则? 我有点糊涂了...
我做了一些研究。 请纠正我,如果我错了。
如果我的理解是正确的,它是所有关于扔在分配和正在发生的事情已分配内存。 所以,如果我在构造函数为它分配内存丢失,它不能在异常的析构函数,这将产生一个内存泄漏被释放。 但它的好扔之前分配这一点,所以异常干净。
我尝试这样做:
struct xexception {
int *ttt[10];
xexception() {
ttt[0] = new int[0xfffffffL];
ttt[1] = new int[0xfffffffL];
ttt[2] = new int[0xfffffffL];
ttt[3] = new int[0xfffffffL];
ttt[4] = new int[0xfffffffL];
ttt[5] = new int[0xfffffffL];
ttt[6] = new int[0xfffffffL];
ttt[7] = new int[0xfffffffL];
ttt[8] = new int[0xfffffffL];
ttt[9] = new int[0xfffffffL];
}
~xexception() throw() {
//never happen
delete[] ttt[0];
delete[] ttt[1];
delete[] ttt[2];
delete[] ttt[3];
delete[] ttt[4];
delete[] ttt[5];
delete[] ttt[6];
delete[] ttt[7];
delete[] ttt[8];
delete[] ttt[9];
}
};
int main(int argc, const char *argv[]) {
try {
throw(xexception());
}
catch (const xexception &e) {
std::cerr << "\nttt " << e.ttt[0][0] << std::endl;
}
catch (std::bad_alloc) {
std::cerr << "bad alloc" << std::endl;
}
return 0;
}
其结果是,我得到的bad_alloc的和严重的内存泄露。
现在,如果我之前做了分配,这也抛出bad_alloc的,但在创建异常之前。
我对例外的概念例外是:
谁在乎? 如果我在我的节目一个bad_alloc的,因为memory_leak或其他东西的(我说的是在个人电脑上没有微控制器的程序)我有其他问题。 也许我可以找出一个bad_alloc的发生,但在哪里? 上的功能在我页头(可能的1000一个),或在std::string
(好,我知道它的绳子,但......没有可能操作字符串的记忆......或者其消退)。
try {
// where is the error???
int *x = new int[100]; // here?
....
int *y = new int[100]; // or here?
....
int *z = new int[100];
....
int *w = new int[100];
....
int *t = new int[100];
....
int *f = new int[100];
....
std::string str("asdfasdfasdfasdfasdfasdfasdf"); // maybe here
}
catch (the error) {
....
}
然后? 我要揣摩它是怎么回事? 因此,我会使用的valgrind不会例外。
void foo() {
int *i = new int[1];
foo();
}
try {
foo();
}
chatch( bad_boy ) {
go_exception_handler_go(parameters); // oh, shit happens: also an stack_overflow may happend, cause stack is also full
}
还是我操作的ErrorMessage和日志吧,有什么明确将引发下一个bad_alloc的。
请不要误解我。 因为我已经看到了boost ::例外,我已经重写我的异常类(直到等待一个答案),但我也觉得是不是真的有必要每一粒沙子捡起。