C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]

后端 未结 4 647
故里飘歌
故里飘歌 2020-12-02 01:41

Thanks for all the response.

I reformatted my question to understand the state of the member pointer after the containg class constructor throws an exception

4条回答
  •  一向
    一向 (楼主)
    2020-12-02 01:57

    Not if it was never allocated.

    But instead of NULL being returned by bad allocations via new, you will get an exception std::bad_alloc.

    NULL gets returned by C malloc if an allocation cannot be made.

    You are also correct that if an object is not fully constructed, it will not be destructed. So if you have a successful allocation on the heap in a constructor, and then an exception is thrown, that will lead to a memory leak.

    You could also consider having a zombie state instead of throwing an exception. Some of the standard C++ library does this. In which case the object is not in a valid state and can be checked if it is in a valid state via another method.

    Generally throwing exceptions in constructors is best though.

    See my answer here for an extended discussion.

提交回复
热议问题