我正在编写一些代码来检查特定的 MIDI 设备是否已插入,如果没有,则代码每 5 秒重新检查一次,直到插入为止。
我的问题出现在检查设备列表时 - 外部库没有重新检查端口的功能,因为它只在类的构造函数中执行此操作。
我能看到让我的代码重新检查设备列表的唯一方法是重新初始化类对象。
类对象在头文件中声明为ofxMidiIn midiIn;
,因为它在 cpp 文件中全局使用。问题是,如果我在 cpp 中的函数内“重新声明”,它似乎不会替换全局范围内的对象,即使它在本地很好。
用伪代码来澄清:
在.h中:
class foo {
ofxMidiIn midiIn; //first initialization does a port scan
};
在.cpp中:
void foo::setup(){
midiIn.listPorts(); //if this fails the recheck is triggered every 5 secs
}
void foo::run(){
//if setup failed then while (!recheck());
}
bool foo::recheck(){
ofxMidiIn midiIn;
midiIn.listPorts(); //this works in this (local) scope, but doesn't reassign midiIn globally
}
通过使用placement new
您可以重新调用构造函数:
bool foo::recheck()
{
new (&midiIn) ofxMidiIn();
midiIn.listPorts();
}
线路new (&midiIn) ofxMidiIn()
将重新构建midiIn
在它自己的内存区域中,通过调用构造函数ofxMidiIn
。然而,如果ofxMidiIn
有指针,并且您已在前一个对象中为它们分配了内存。你将会泄漏内存。不过,您可以显式调用析构函数,写为:
(&midiIn)->~ofxMidiIn(); //call the destructor explicitly
new (&midiIn) ofxMidiIn(); //then do this!
Demo : http://ideone.com/OaUtw http://ideone.com/OaUtw
无论如何,我相信更好、更干净的解决方案是将变量设置为pointer as:
ofxMidiIn *midiIn;
然后使用new
and delete
。当你这样做时new
下次,必须删除前一个对象,方法如下:
bool foo::recheck()
{
delete midiIn; //must do this if it already has been allocated memory!
midiIn = new ofxMidiIn();
midiIn->listPorts();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)