create a class that only can new.
class OnlyCanNew {
public:
OnlyCanNew() {}
void print() const {
std::cout << "I can run." << std::endl;
}
void destory() { // This function invokes the destructor.
delete this; // NOTE: is 'this', not '*this'.
}
private:
~OnlyCanNew(){} // Make the destructor become the private function.
};
int main() {
OnlyCanNew* on = new OnlyCanNew;
on->print();
on->destory();
return 0;
}