使用新放置与 Teensy 3.

Using placement new with the Teensy 3

本文关键字:Teensy 新放      更新时间:2023-10-16

我在Arduino/Teensy环境中有一个C++类,该类在".h"文件中定义。在".cpp"文件中,我正在尝试使用一些代码进行"新放置"。我收到以下错误:

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*)'

所以看起来问题在于,在 Teensy 核心库中,没有定义新的位置 - 运算符只期望一个参数,而不是两个参数。

如果我像这样在".h"文件中定义我自己的放置 new 实现并将其包含在上述类的头文件中:

#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

它似乎有效,但前提是我在头文件内的方法中使用放置 new。如果我将代码移出标头并移入".cpp"实现文件,我会收到一个类似的错误,即只需要一个参数。

有没有办法解决这个问题?

我发现解决这个问题的最直接方法是简单地打开

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

并把原型

void *operator new(size_t size, void *ptr);
void operator delete(void *obj, void *alloc);

那里对运算符进行多次重载,然后在关联的".cpp"文件中使用函数。

不知道为什么一开始就不包括在内...