我班上的构造函数检查某些条件.在某些情况下,它应该打破对象的创建.我应该在那里放置析构函数还是只返回声明?
它是这样的:
代码中的某个地方:
new Obj( string );
Run Code Online (Sandbox Code Playgroud)
和我的构造函数:
Obj::Obj( string ) {
if( string == "something" ) {
// should I put this here or only return?
Obj::~Obj();
return;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以在创建对象之前检查条件,但我只是想知道它是否正确(如果没有内存泄漏),因为它编译得很好而不会在运行时崩溃.
Luc*_*ore 10
你也不应该抛出异常.
不会创建任何对象,这是处理这种情况的惯用方法.
您需要在调用上下文(或更高版本)中处理异常.
Obj::Obj( string ) {
if( string == "something" ) {
// should I put this here or only return?
throw ObjectCouldNotBeCreatedException();
}
}
Run Code Online (Sandbox Code Playgroud)