Classes that can only be instantiated on heap memory: The destructor is defined as private, the destructor cannot be called automatically on the stack, and can only be called manually. You can also define a constructor as private, but you need to manually write a function to implement the object's construction.
Classes that can only be instantiated on stack memory: The function operator new AND operator delete are defined as private, so when you create an object using the new operator, you cannot call operator New,delete destroy the object or call operator Delete
#include <iostream>using namespace std;//class class cheaponly{public that can only be instantiated on heap memory: Cheaponly () {cout << "constructor of cheaponly!" << endl;} Void destroy () const{delete this;} Private:~cheaponly () {cout << "destructor of cheaponly!" << endl;}};/ /class that can only be instantiated on the stack memory, that is, the class cannot be constructed using new, and the operator new is privatized class cstackonly{public:cstackonly () {cout << "constructor of cstackonly!" << endl;} ~cstackonly () {cout << "destrucotr of cstackonly!" << endl;} Private:void* operator new (size_t size) {}void operator delete (void * ptr) {} };int main () {Cheaponly* pheap = new cheaponly;pheap->destroy (); cstackonly objstack;return 0;} Classes that can only be instantiated on heap memory// the following class can also be generated only on heap memory, with constructors and destructors defined as private,//but objects can be created through the static function of the class, but this object cannot be inherited. class finalclass{Public:static finalclass* getinstance () {cout << "constructor of the Class " << endl;return new finalclass;} Static void deleteinstance (finalclass* pinstance) {cout << "Destructor of the class "&NBSP;<<&NBSP;ENDL;DELETE&NBSP;PINSTANCE;PINSTANCE&NBSP;=&NBSP;0;} Private:finalclass () {}~finalclass () {}};int main () {finalclass* fc = finalclass: : getinstance (); Finalclass::D eleteinstance (FC); return 0;}
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1765117
Design a class that can only be instantiated on heap memory and a class that can only be instantiated on stack memory