Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

c++ - What's the difference between "= default" destructor and empty destructor?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 with std::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:

~A() = default;

and:

~A() {};

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...