Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

constructor - Why do C++ objects have a default destructor?

When I don't declare a constructor for example, the compiler will provide me with a default constructor that will have no arguments and no definition (empty body), and thus, will take no action.

So, if I'm finished with an object for example, wouldn't the default destructor reallocate (free) memory used by the object? If it doesn't, why are we getting it?

And, maybe the same question applies to the default constructor. If it does nothing, why is it created for us by default?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's wrong to say that a compiler-generated default constructor takes no action. It is equivalent to a user-defined constructor with an empty body and an empty initializer list, but that doesn't mean it takes no action. Here is what it does:

  1. It calls the base class'es default constructor.
  2. It initializes the vtable pointer, if the class is polymorphic.
  3. It calls the default constructors of all members that have them. If there is a member with some constructors, but without a default one, then it's a compile-time error.

And only if a class is not polymorphic, has no base class and has no members that require construction, then a compiler-generated default constructor does nothing. But even then a default constructor is sometimes necessary for the reasons explained in other answers.

The same goes for the destructor - it calls base class'es destructor and destructors of all members which have them, so it isn't true in general case that a compiler-generated destructor does nothing.

But memory allocation really has nothing to do with this. The memory is allocated before the constructor is called, and it is freed only after the last destructor has finished.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...