Register forum user name Search FAQ

Gammon Forum

Notice: Any messages purporting to come from this site telling you that your password has expired, or that you need to verify your details, confirm your email, resolve issues, making threats, or asking for money, are spam. We do not email users with any such messages. If you have lost your password you can obtain a new one by using the password reset link.

Due to spam on this forum, all posts now need moderator approval.

 Entire forum ➜ Programming ➜ General ➜ Implementing new and delete

Implementing new and delete

It is now over 60 days since the last post. This thread is closed.     Refresh page


Posted by Nick Gammon   Australia  (23,173 posts)  Bio   Forum Administrator
Date Sat 13 Aug 2011 04:25 AM (UTC)

Amended on Thu 31 May 2012 04:09 AM (UTC) by Nick Gammon

Message
I keep forgetting how to do a new/delete sequence on platforms that don't have it inbuilt (like the Arduino) so I'll document it right here:


// new
inline void * operator new (size_t size) { return malloc (size); }
// placement new
void * operator new (size_t size, void * ptr) { return ptr; }
// delete
void operator delete (void * ptr) { free (ptr); }

// new array
void * operator new [] (size_t size) { return malloc (size); }
// placement new array
void * operator new [] (size_t size, void * ptr) { return ptr; }
// delete array
void operator delete [] (void * ptr) { free (ptr); } 


Placement new is used to invoke the constructor for an object that *you* supply the memory for at runtime ...


char buffer [sizeof (MyClass)];
MyClass *instance;

void init() 
  {
  // call constructor using supplied memory
  instance = new (buffer) MyClass ();

  ...  


  // call destructor if necessary
  instance->~MyClass();  
  }


[EDIT] Modified 31 May 2012 to add arrays.

- Nick Gammon

www.gammon.com.au, www.mushclient.com
Top

The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).

To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.


5,484 views.

It is now over 60 days since the last post. This thread is closed.     Refresh page

Go to topic:           Search the forum


[Go to top] top

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.