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

Zak*_*nry 4 c++ constructor scope initialization

我正在编写一些代码,用于检查是否插入了特定的midi设备,如果不是代码,则每隔5秒重新检查一次,直到插入为止.

我的问题出现在检查设备列表中 - 外部库没有重新检查端口的功能,因为它只在类的构造函数中执行.

我能看到让我的代码重新检查设备列表的唯一方法是重新初始化类对象.

类对象在头文件中声明为ofxMidiIn midiIn;,因为它在cpp文件中全局使用.问题是,如果我在cpp中的一个函数内'重新声明',它似乎不会替换全局范围内的对象,即使它在本地很好.

用伪代码澄清:

在.h:

class foo {

    ofxMidiIn midiIn; //first initialization does a port scan

};
Run Code Online (Sandbox Code Playgroud)

在.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

}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 10

通过使用,placement new您可以重新调用构造函数:

bool foo::recheck()
{
    new (&midiIn) ofxMidiIn();
    midiIn.listPorts(); 
}
Run Code Online (Sandbox Code Playgroud)

该行将通过调用其构造new (&midiIn) ofxMidiIn()函数midiIn在其自己的内存区域中重新构造ofxMidiIn.但是,如果ofxMidiIn有指针,这种方法会产生问题,并且您在前一个对象中为它们分配了内存.你会泄漏记忆.您可以通过以下方式显式调用析构函数:

    (&midiIn)->~ofxMidiIn();   //call the destructor explicitly
    new (&midiIn) ofxMidiIn(); //then do this!
Run Code Online (Sandbox Code Playgroud)

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


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

ofxMidiIn *midiIn;
Run Code Online (Sandbox Code Playgroud)

然后使用newdelete.当你new下次这样做时,必须删除前一个对象,写为:

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