Reputation: 41
From IBM.com (https://www.ibm.com/support/knowledgecenter/ssw_ibm_i_72/rzarg/cplr380.htm)
A destructor of a class A is trivial if all the following are true:
- It is implicitly defined
- All the direct base classes of A have trivial destructors
- The classes of all the nonstatic data members of A have trivial destructors destructor of a class A is trivial (not necessary) if all the following are true:
Interpretations:
The constructors that were used within the class were imported. No new constructors were created within the class.
From the website: “A direct base class is a base class that appears directly as a base specifier in the declaration of its derived class.” And the rabbit hole continues as I wonder what is a base specifier. Please help.
The data types are primitive.
Please comment if any of my interpretations are wrong or can be further simplified for clarity.
class Foo {
public:
~Foo() { s = “”; x = 0; vi.clear(); }
private:
string s;
int x;
vector<int> vi;
};
Given that it is considered a bad practice to create a destructor as shown above, is there an easy way to remember when it is necessary to create a destructor?
Upvotes: 1
Views: 298
Reputation: 122298
The rule of zero (from cppreference):
Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators.
I like how cppreference is very explicit about it.
Either you write a class that does nothing but manage a resource. In that case you do need to read about the rule of 3/5 (same link). This should be rare, because there are containers and smart pointers that already do mangage resources for you. However a "resource" that should be RAII enabled can be more than just memory, it can be a file, a DB-connection, etc.
Or you write a class the does not manage a resource. In that case you do not need to write a destructor.
Upvotes: 2