Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 84,808 C++ Programmers. There are 2,164 online right now! Ask your question and get quick answers from Dream.In.Code experts. Join the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a C++ Expert
Powered by LivePerson.com

Register to Make This Box Go Away!

Restriction on creation of object into heap, stack or static memory

 
Reply to this topicStart new topic

> Restriction on creation of object into heap, stack or static memory, Restriction on creation of object into heap, stackor static memory

asadullah.ansari
Group Icon



post 12 Mar, 2008 - 04:10 AM
Post #1


Example 1: Object should be created Only On Heap memory.Idea is that make
constructor as private so that no one create on stack. But one drawback is
that constructor can be overloaded so better make destructor as private
member of class because Destructor can'nt be overloaded. It's very safe
to make destructor as private member of class for this purpose.
CODE

class HeapOnly
{
public:
void DestroyMe() //This function will call destructor
{
   delete this;   // Current object will be deleted means destructor
}
private:
~HeapOnly();     // destructor only can be call by member function
};


Now you can test above class.
CODE


int main()
{
HeapOnly obj;  //error will come
HeapOnly * ptr = new HeapOnly;  // Object created on heap
ptr->DestroyMe()                // Object deallocated
}


Example 2: Object should be created Only On stack memory or static memory. Idea
is that just overload the new and delete operator and make it private member
and dummy implemetation.

CODE

class autoOnly
{
  public:
    autoOnly()
    {
   ;
    }
    ~autoOnly()
    {
   ;
    }
  private:
    void* operator new(size_t)
    {
      // Dummy Implementation
    }
    void* operator new[](size_t)
    {
      // Dummy Implementation
    }
    void operator delete(void*)
    {
       // Dummy Implementation
    }
    void operator delete[](void*)
    {
      //Dummy Implementation
    }
};


Now you can test it .

int main()
{
autoOnly *ptr= new autoOnly; // Error " cannt Access private member
autoOnly obj; // Created on stack
static autoOnly obj1; //Created on static memory
return 0;
}


By
Asadullah Ansari


Register to Make This Ad Go Away!


Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 5/9/08 07:46AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month