【问题标题】:Using placement new with the Teensy 3在 Teensy 3 中使用新位置
【发布时间】:2016-02-17 19:01:59
【问题描述】:

我在 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 核心库中放置 new 没有定义 - 操作员只需要一个参数,而不是两个。

如果我像这样在“.h”文件中定义自己的placement 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

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

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

【问题讨论】:

  • static_cast&lt;AudioStream*&gt; 是可疑的,如果标题中有,您的 operator new/delete 需要为 inline。 (而且我认为它们应该只在 cpp 文件中)。
  • @Jarod42 我试图这样做的原因是有几个不同的类派生自 AudioStream,我想将它们上载到它们的父类,所以在我在这里定义的类中我只需要保留一个指针(AudioStream 类型)指向放置它们的缓冲区,而不是为每种类型保留一个单独的指针和一堆逻辑来确定从“new”返回的指针应该放在哪里跨度>
  • 基本上问题是在我使用的库中,在“AudioStream”类中,只有流的“更新”函数被声明为“虚拟”,所以如果我要存储一个指向“AudioStream”所有子类的超类的指针我相信每次我想调用一个方法而不是它的一个子类的方法时,我都必须向下转换指针
  • 你知道为什么你做新的安置吗? _waveform 是什么?它是如何初始化的?
  • 正如这个问题的公认答案:stackoverflow.com/questions/35371369/… _waveform 是私有变量部分联合中 AudioStream 的子类之一,然后我使用以下(_current音是 AudioStream 类型的指针):_current_tone = static_cast&lt;AudioStream*&gt;(new (&amp;_waveform) AudioSynthWaveform);

标签: c++ arduino embedded placement-new teensy


【解决方案1】:

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

/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”文件中的函数。

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

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 1970-01-01
    • 2015-02-09
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多