I want to prevent the user of my class from using it as an automatic variable, so I write code like this:
class A {
private:
~A() = default;
};
int main() {
A a;
}
I expect that the code won't be compiled, but g++ compiles it without error.
However, when I change the code to:
class A {
private:
~A(){}
};
int main() {
A a;
}
Now, g++ gives the error that ~A()
is private, as is my expectation.
What's the difference between a "= default" destructor and an empty destructor?
Your first example should not compile. This represents a bug in the compiler that it does compile. This bug is fixed in gcc 4.9 and later.
The destructor defined with
= default
is trivial in this case. This can be detected withstd::is_trivially_destructible<A>::value
.Update
C++11 (and C++14) state that if one has a user-declared destructor (and if you don't have either user-declared move special member), then the implicit generation of the copy constructor and copy assignment operator still happen, but that behavior is deprecated. Meaning if you rely on it, your compiler might give you a deprecation warning (or might not).
Both:
and:
are user-declared, and so they have no difference with respect to this point. If you use either of these forms (and don't declare move members), you should explicitly default, explicitly delete, or explicitly provide your copy members in order to avoid relying on deprecated behavior.
If you do declare move members (with or without declaring a destructor), then the copy members are implicitly deleted.