Uses of destructor = delete;

前端 未结 5 1262
悲哀的现实
悲哀的现实 2020-12-29 19:41

Consider the following class:

struct S { ~S() = delete; };

Shortly and for the purpose of the question: I cannot create instances of

5条回答
  •  既然无缘
    2020-12-29 20:29

    Why mark a destructor as delete?

    To prevent the destructor from being invoked, of course ;)

    What are the use cases?

    I can see at least 3 different uses:

    1. The class should never be instantiated; in this case I would also expect a deleted default constructor.
    2. An instance of this class should be leaked; for example, a logging singleton instance
    3. An instance of this class can only be created and disposed off by a specific mechanism; this could notably occur when using FFI

    To illustrate the latter point, imagine a C interface:

    struct Handle { /**/ };
    
    Handle* xyz_create();
    void xyz_dispose(Handle*);
    

    In C++, you would want to wrap it in a unique_ptr to automate the release, but what if you accidentally write: unique_ptr? It's a run-time disaster!

    So instead, you can tweak the class definition:

    struct Handle { /**/ ~Handle() = delete; };
    

    and then the compiler will choke on unique_ptr forcing you to correctly use unique_ptr instead.

提交回复
热议问题