Yes you can, as of the Arduino IDE version 1.0.5 you can use the standard new
& delete
operators in your code. However if you use an older version it is still possible to add the functionality yourself.
To manually add in the functions yourself, copy the code snippets below straight into your sketch, or separated into a .h/.cpp combination.
- Prototypes.
If you are copying directly into your sketch, these prototypes are not needed. If you wish to use the functionality in multiple .cpp files, not just the sketch, you will need to place these definitions in a header file. Once in a header, you can include it into all the files the use
new
ordelete
operators.void *operator new( size_t size ); void *operator new[]( size_t size ); void operator delete( void *ptr ); void operator delete[]( void *ptr );
- Defintions.
As shown in the code below, the actual functions are simply wrappers for the standard memory allocator functions
malloc()
andfree()
. The difference betweennew
andmalloc()
is the functionality provided by C++; where one can allocate memory and construct an object into the allocation, all within a single statement. Primarily thenew
anddelete
operators are designed to look after creation and destruction of an object. For a detailed description, visit this article: How to use dynamic memory.void *operator new( size_t size ){ return malloc( size ); } void *operator new[]( size_t size ){ return malloc( size ); } void operator delete( void *ptr ){ if( ptr ) free( ptr ); } void operator delete[]( void *ptr ){ if( ptr ) free( ptr ); }
Take note that these functions conform to the standard and do not require you to check if a pointer is non-null to delete. This is in opposition to the Arduino core implementations which do not check for a null pointer.
- Placement versions.
The
placement new
andplacement delete
operators are not provided in any distribution of Arduino, however they are here for your use.void *operator new( size_t size, void *ptr ){ return ptr; } void operator delete( void *obj, void *alloc ){ return; }
As you can see,
placement new
allocates no memory, andplacement delete
does nothing at all, I added it for completeness, its theplacement new
operator that really matters. For an indepth look at the placement operators, there is an FAQ link below.
This document is one of four articles covering dynamic memory usage on the Arduino.
- How to use dynamic memory
- Mixing malloc and new
- Placement new and delete