Minimalistic destructors?
We have some issue with my friend. Assume, we have a class which implements database connection, like this:
class DB
{
void Connect();
void Disconnect();
// ...
~DB();
};
In my opinion, destructo开发者_如何转开发r should be minimalistic, which means destructor should not call Disconnect method when connection was established. I think, that this should be done by separate method (disconnect() in this example). Am I correct, or my friend is?
PS. Community Wiki?
Your destructor should be enough to clean up all the resources that were acquired during the object lifetime. This might or might not include ending connnections. Otherwise who will do the cleanup if an exception is thrown?
The RAII idioms says: acquire in the constructor and release in the deconstructor. You must guarantee that your deconstructor will NOT throw anything. Otherwise you will have core dump (or undefined behaviour) if your object deconstructor will throw an exception during the stack-unwind.
Also in your specific case I will probably implement a reference counting mechanism, and call the disconnect just when you haven't any more object using the connection.
According to the syntax it looks like C++. Am I correct? Because if so, you can (and it is highly recommended to) use the RAII idiom. That means that you aquire the DB connection on construction, free it (disconnect) on destruction.
Good reference: What's RAII All About?
From the class user point of view, I believe it is better to try and disconnect
the database connection when it should instead of assuming the destructor will do the job.
However, bad things happen, most notably exceptions, and you must guarantee that cleanup will occur regardless of what happened. This is why your destructor should nevertheless disconnect
if necessary (i.e: if it hasn't been explicitly called by the user).
精彩评论