I have the below code snippet which is to demonstrate use-case of function-try-block for constructor. Because the constructor of Controller
throws no object of it gets created successfully, i.e. the client_
member variable should no longer exist too when exception is thrown, is that correct? If so then is that safe to call deinit()
which is to clean-up the client_
? If not safe, say if client_
was a raw pointer which then how would I catch the exception and do clean-up stuff for it?
class Client {
public:
Client() { std::cout << "Client()" << std::endl; }
~Client() { std::cout << "~Client()" << std::endl; }
void Start() { throw "Start() failed with exception"; }
};
class Controller {
private:
std::shared_ptr<Client> client_;
public:
Controller() try {
client_ = std::make_shared<Client>();
client_->Start();
} catch (...) {
deinit();
}
~Controller() {
deinit();
}
private:
void deinit() {
if (client_) {
client_.reset();
}
}
};