What (not) to do in a constructor

后端 未结 13 1680
悲&欢浪女
悲&欢浪女 2020-12-12 17:33

I want to ask you for your best practices regarding constructors in C++. I am not quite sure what I should do in a constructor and what not.

Should I only use it for

13条回答
  •  眼角桃花
    2020-12-12 17:44

    You MAY throw from a constructor, and it is often the better option than creating a zombie object, i.e. an object that has a "failed" state.

    You should, however, never throw from a destructor.

    The compiler WILL know what order the member objects are constructed - the order they appear in the header. The destructor will however not be called as you said, which means if you are calling new multiple times within a constructor you cannot rely on your destructor calling the deletes for you. If you put them into smart pointer objects that is not a problem as these objects will be deleted. If you want them as raw pointers then put them temporarily into auto_ptr objects until you know your constructor will no longer throw, then call release() on all your auto_ptrs.

提交回复
热议问题