根据我的理解(基于this page),我们想在基类中使用非虚拟和受保护的析构函数的唯一情况如下:
#include <iostream>
struct unary_function {
protected:
~unary_function() {
std::cout << "unary_function" << std::endl;
}
};
struct IsOdd : public unary_function {
public:
bool operator()(int number) {
return (number % 2 != 0);
}
};
void f(unary_function *f) {
// compile error
// delete f;
}
int main() {
// unary_function *a = new IsOdd;
// delete a;
IsOdd *a = new IsOdd;
delete a;
getchar();
return 0;
}
因此,您只能这样做:
IsOdd *a = new IsOdd;
delete a;
或者
IsOdd c;
从来没有这些:
unary_function *a = new IsOdd;
delete a;
因此,对于非虚拟受保护的析构函数,当您尝试使用它时编译器会给出错误
void f(unary_function *f) {
delete f;
// this function couldn't get compiled because of this delete.
// you would have to use the derived class as the parameter
}