gpt4 book ai didi

c++ - 如何(重新)调用初始化对象的构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:37 24 4
gpt4 key购买 nike

我正在编写一些代码来检查是否插入了特定的 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() 将通过调用 ofxMidiIn 的构造函数在其自己的内存区域中重新构造 midiIn .但是,如果 ofxMidiIn 有指针,并且您已经在前一个对象中为它们分配了内存,这种方法就会产生问题。你会泄漏内存。你可以显式地调用析构函数,写成:

    (&midiIn)->~ofxMidiIn();   //call the destructor explicitly
new (&midiIn) ofxMidiIn(); //then do this!

演示:http://ideone.com/OaUtw


无论如何,我相信更好和更干净的解决方案是将变量作为指针作为:

ofxMidiIn *midiIn;

然后使用newdelete。并且下次做new时,必须删除之前的对象,写成:

bool foo::recheck()
{
delete midiIn; //must do this if it already has been allocated memory!
midiIn = new ofxMidiIn();
midiIn->listPorts();
}

关于c++ - 如何(重新)调用初始化对象的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6868363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com