vendredi 2 janvier 2015

C++11's deleted destructor in derived class


class B {
int i;
public:
B(int param) : i(param) {}
~B() = delete;
};
class D : public B {
int i2;
public:
D(int p1, int p2) : B(p1), i2(p2) {}
~D() = delete;
};

int main() {
B* instance = new D(1,2);
return 0;
}


cl test.cpp:



Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x86
Copyright (C) Microsoft Corporation. All rights reserved.

test.cpp
test.cpp(11) : error C2280: 'B::~B(void)' : attempting to reference a deleted function
test.cpp(6) : see declaration of 'B::~B'


(There is one emply line above the code, so these are one off. sorry)


I have some special classes(one base and many derived) that for performance reasons are always allocated in a stack like memory arena. They don't get any destructor calls(and by design they don't need to). This can be bad if some programmer after me decide that he really needs to put a vector inside.(memory leaks, these classes are spawned in large numbers and live a few function calls, ouch)


What I tried is using C++11 deleted destructors. My questions are:



  • Why is this not working?

  • Any better ideas how to forbid destructors or non-PODs inside the class?


Aucun commentaire:

Enregistrer un commentaire