What is a non-trivial destructor in C++?

送分小仙女□ 提交于 2019-11-29 17:38:08

问题


I was reading this which mentions destructors being trivial and non-trivial.

A class has a non-trivial destructor if it either has an explicitly defined destructor, or if it has a member object or a base class that has a non-trivial destructor.

In example, I have a class,

class C {
    public:
     ~C(); // not explicitly declared.
};

If C::~C() is implicitly defined does it make a trival dtor?


回答1:


You are getting your words mixed up. Your example does indeed declare an explicit destructor. You just forget to define it, too, so you'll get a linker error.

The rule is very straight-forward: Does your class have an explicit destructor? If yes, you're non-trivial. If no, check each non-static member object; if any of them are non-trivial, then you're non-trivial.




回答2:


So you mean, the entire declaration of C is this:

class C { };

?

Then, yes: Since C has no member objects and no base classes, it therefore has no member objects with non-trivial destructors and no base classes with non-trivial destructors, so its implicitly-defined destructor is a trivial one.




回答3:


I think in general it refers to a destructor that actually does something such as:

  • Release memory
  • Close a connection to database
  • Or take care of any resource that needs to be released

In this case the destructor does nothing. According to the description, technically it may be 'non-trivial' because it defines a constructor, but it matters not, since it does nothing anyway.



来源:https://stackoverflow.com/questions/8190879/what-is-a-non-trivial-destructor-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!