在 C++ 构造函数中使用 new 运算符是否正确?
Is it right to use new operator inside C++ constructor?
class test{
int value;
};
class sample{
sample(){
test *var = new test();
}
};
int main(){
sample foo;
//what will happen here if sample constructor fails to allocate its memory?
}
在 C++ 构造函数中使用 new
运算符是否正确?
如果 sample
构造函数分配内存失败,这里会发生什么?
what will happen here if sample constructor fails to allocate a memory?
它将抛出一个 std::bad_alloc
异常并且可以在 main()
中通过捕获它来清理:
int main() {
try {
sample foo;
// Work with foo ...
}
catch(const std::bad_alloc& ba) {
std::err << "Not enough memory available. Caught 'bad_alloc' exception: '"
<< ba.what() << "'" << std::endl;
}
}
new
失败时将抛出 bad_alloc
异常。
当构造函数异常退出时,对象永远不会到达构造点。它的析构函数不 运行.
如果在构造函数体内抛出异常,对象的所有成员变量都会被销毁(通过析构函数调用)。如果异常是从一个成员的构造函数中抛出的,那么前面成员的析构函数运行。关键是撤消构造函数到目前为止所做的任何事情,不多也不少。
这一切都不应该有任何异味。请注意成员析构函数将始终正常运行。这可能涉及对 class 不变量更加挑剔。 C++ 想要处理异常情况,所以你不需要写很多极端情况……但另一方面是极端情况仍然存在,隐含和不言而喻。
class test{
int value;
};
class sample{
sample(){
test *var = new test();
}
};
int main(){
sample foo;
//what will happen here if sample constructor fails to allocate its memory?
}
在 C++ 构造函数中使用 new
运算符是否正确?
如果 sample
构造函数分配内存失败,这里会发生什么?
what will happen here if sample constructor fails to allocate a memory?
它将抛出一个 std::bad_alloc
异常并且可以在 main()
中通过捕获它来清理:
int main() {
try {
sample foo;
// Work with foo ...
}
catch(const std::bad_alloc& ba) {
std::err << "Not enough memory available. Caught 'bad_alloc' exception: '"
<< ba.what() << "'" << std::endl;
}
}
new
失败时将抛出 bad_alloc
异常。
当构造函数异常退出时,对象永远不会到达构造点。它的析构函数不 运行.
如果在构造函数体内抛出异常,对象的所有成员变量都会被销毁(通过析构函数调用)。如果异常是从一个成员的构造函数中抛出的,那么前面成员的析构函数运行。关键是撤消构造函数到目前为止所做的任何事情,不多也不少。
这一切都不应该有任何异味。请注意成员析构函数将始终正常运行。这可能涉及对 class 不变量更加挑剔。 C++ 想要处理异常情况,所以你不需要写很多极端情况……但另一方面是极端情况仍然存在,隐含和不言而喻。