Using placement new with the Teensy 3

513 Views Asked by At

I have a C++ class in the Arduino/Teensy environment which is defined in a ".h" file. Within the ".cpp" file I'm attempting to do "placement new" with some code. I'm getting the following error:

oscillator.h:17: error: no matching function for call to 'operator new(sizetype, AudioSynthWaveform*)'
_current_tone = static_cast<AudioStream*>(new (&_waveform) AudioSynthWaveform);
^
/tmp/build578ae2c22656d87e9d0d68db21416349.tmp/sketch/oscillator.h:17:68: note: candidate is:
In file included from /opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/Printable.h:25:0,
from /opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/Print.h:39,
from /opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/Stream.h:24,
from /opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/HardwareSerial.h:169,
from /opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/WProgram.h:16,
from /opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/Arduino.h:1,
from /tmp/build578ae2c22656d87e9d0d68db21416349.tmp/sketch/Synthesizer.ino.cpp:1:
/opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/new.h:12:8: note: void* operator new(size_t)
void * operator new(size_t size);
^
/opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/new.h:12:8: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'operator new(sizetype, AudioSynthWaveform*)'

So it looks like problem is that in the Teensy core libraries placement new isn't defined - the operator is expecting only a single argument, not two.

If I define my own implementation of placement new in a ".h" file like so and include it in the header file of the above class:

#ifndef NEW_H
#define NEW_H

void *operator new(size_t size, void *ptr){
  return ptr;
}

void operator delete(void *obj, void *alloc){
  return;
}

#endif //NEW_H

it seems to work, but only if I use placement new in a method within the header file. I get a similar error about only a single argument being expected if I move the code out of the header and into the ".cpp" implementation file.

Is there a way to resolve this?

1

There are 1 best solutions below

0
On

I found the most straightforward way to resolve this is to simply open up

/opt/arduino-1.6.7/hardware/teensy/avr/cores/teensy3/new.h

And put the prototypes

void *operator new(size_t size, void *ptr);

void operator delete(void *obj, void *alloc);

there to multiple overload the operator, and then the functions in the associated ".cpp" file.

Not sure why that wasn't included to begin with...