Restrict dynamic allocation of objects | C++

/Restrict dynamic allocation of objects | C++

C++ programming language allows both auto (or stack allocated) and dynamically allocated objects. In Java & C#, all objects must be dynamically allocated using new.
C++ supports stack allocated objects for the reason of runtime efficiency. Stack based objects are implicitly managed by C++ compiler. They are destroyed when they go out of scope and dynamically allocated objects must be manually released, using delete operator otherwise memory leak occurs.

To restrict dynamic allocation a class ‘Test’ in C++ i.e.

Test* t = new Test; // Compile time error
Test t;             // OK

 

The idea of is to keep new operator function private so that new cannot be called.

// Objects of ObjectAllocation can not be dynamically allocated 
class ObjectAllocation
{
    // new operator function is private 
    void* operator new(size_t size); 
    int x; 

public:
    ObjectAllocation()          { x = 9; cout << "Constructor is called\n"; } 
    ~ObjectAllocation()         { cout << "Destructor is executed\n"; } 
};

int main() 
{
    ObjectAllocation   *obj=new ObjectAllocation();  //  Throw a compile time error. 
    ObjectAllocation t;                              // Object is allocated at compile time 
    return 0; 
}

 

May 10th, 2019|Categories: Programming|
avatar
  Subscribe  
Notify of