When should I prevent implicit destruction? How does it work?

南楼画角 提交于 2019-12-14 04:01:25

问题


I know that I can declare a destructor =delete or private in order to prevent the program from implicitly deleting the object at the end of scope. I also know that if it's private, I can have a member function that can explicitly call the destructor whenever I call it: void kill() { this–>~A(); }

My questions are:

  • Why would I ever want to prevent implicit destruction? Please give an example

  • What would =delete do? Does it make sure the destructor never runs? So the object will exist forever outside its scope?


回答1:


Idioms like a private destructor are generally used to prevent other programmers from performing certain operations with your type. A private destructor in particular prevents the following:

  • Declaration of a type of your instance on the stack
  • Manual deletion of an instance of your type via the delete keyword
  • Manual destructor calls

Doing any of these will raise a compile error that is not trivial to work around. The error is usually a message from the author to a user that they should not perform one or all of these operations, instead the author may want them to:

  • Call factory functions to destroy instances of this type (typically coupled with private constructors). Providing extra context on construction and destruction can provide optimization opportunities or prevent API misuse when a batched operation is much more efficient than a "one off" allocation.
  • Not allocate any instances of this type (maybe it's a singleton)

Consider writing a type that manages a hardware interface, allowing the user to simply delete the instance might leave hardware in an undesirable state - so why even allow it? Yes, at some point the API can be built up to abstract away this difficulty - but at some basic level 'fragile' functionality needs to be exposed.

=delete is the 'new' bullet proof way of preventing user error. Unlike the private copy constructor it cannot be circumvented via the 'friend' keyword. It also tends to read better, in that it tells the user of the code in a consistent fashion that this feature is not available. My understanding is that =delete was introduced in c++11 as a replacement for the "no copy/no delete idioms".



来源:https://stackoverflow.com/questions/18840058/when-should-i-prevent-implicit-destruction-how-does-it-work

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