Uses of destructor = delete;

前端 未结 5 1263
悲哀的现实
悲哀的现实 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:36

    one scenario could be the prevention of wrong deallocation:

    #include 
    
    struct S {
        ~S() = delete;
    };
    
    
    int main() {
    
        S* obj= (S*) malloc(sizeof(S));
    
        // correct
        free(obj);
    
        // error
        delete obj;
    
        return 0;
    
    }
    

    this is very rudimentary, but applies to any special allocation/deallocation-process (e.g. a factory)

    a more 'c++'-style example

    struct data {
        //...
    };
    
    struct data_protected {
        ~data_protected() = delete;
        data d;
    };
    
    struct data_factory {
    
    
        ~data_factory() {
            for (data* d : data_container) {
                // this is safe, because no one can call 'delete' on d
                delete d;
            }
        }
    
        data_protected* createData() {
            data* d = new data();
            data_container.push_back(d);
            return (data_protected*)d;
        }
    
    
    
        std::vector data_container;
    };
    

提交回复
热议问题