Ask Your Question
4

If the constructor throws, is it safe to call a class member function that performs cleanup operations on member variables?

asked 2023-05-24 13:27:31 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-24 13:46:02 +0000

lalupa gravatar image

No, it is not safe to call a class member function that performs cleanup operations on member variables if the constructor throws an exception. Since the constructor was not able to complete properly, the expected state of the object will not be guaranteed, and it may result in undefined behavior when calling other member functions. Instead, it is better to use a destructor to perform the cleanup operation, as it is guaranteed to be called when an object goes out of scope or is deleted.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-24 13:27:31 +0000

Seen: 11 times

Last updated: May 24 '23