简体   繁体   中英

Breaking creation of object in constructor

Constructor in my class checks for some condition. In some case it should break the creation of the object. Should I put there a destructor or just return statement?

It goes something like this:

Somewhere in the code:

new Obj( string );

and my constructor:

Obj::Obj( string ) {
    if( string == "something" ) {
        // should I put this here or only return?
        Obj::~Obj();
        return;
    }
    // ...
}

I know that I can check the condition before creation of the object, but I just wonder if it's correct (if there are no memory leaks) because it compiles well without crashing at runtime.

Neither, you should throw an exception.

No object will be created and this is the idiomatic way of dealing with this sort of situation.

You'll need to handle the exception in the calling context (or higher).

Obj::Obj( string ) {
    if( string == "something" ) {
        // should I put this here or only return?
        throw ObjectCouldNotBeCreatedException();
    }
}

A return statement will still create the object. In oder to interupt the construction, you should throw an exception instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM