mardi 16 janvier 2018

C++ `if` seems to be taking the wrong branch?

I'm struggling with a non-sensical if statement...

Consider this code in a C++ file

if (coreAudioDevice) {
    delete coreAudioDevice;
    coreAudioDevice = nullptr;
}
coreAudioDevice = AudioDevice::GetDevice(defaultOutputDeviceID, false, coreAudioDevice, true);
if (coreAudioDevice)
{
    coreAudioDevice->setDefaultDevice(true);
    // we use the quick mode which skips initialisation; cache the device name (in AudioDevice)
    // using an immediate, blocking look-up.
    char devName[256];
    coreAudioDevice->GetName(devName, 256);

    AUDINFO ("Using default output device %p #%d=\"%s\".\n",
             defaultOutputDeviceID, coreAudioDevice, coreAudioDevice->GetName());
}
else
    AUDERR ("Failed to obtain a handle on the default device (%p)\n", coreAudioDevice);

calling a function in an ObjC++ file:

AudioDevice *AudioDevice::GetDevice(AudioObjectID devId, bool forInput, AudioDevice *dev, bool quick)
{
    if (dev) {
        if (dev->ID() != devId) {
            delete dev;
        } else {
            return nullptr;
        }
    }
    dev = new AudioDevice(devId, quick, forInput);
    return dev;
}

Which leads to the following terminal output:

ERROR coreaudio.cc:232 [init]: Failed to obtain a handle on the default device (0x7f81a1f1f1b0)

Evidently the if shouldn't fail because coreAudioDevice supposedly is NULL and then print a non-null value for this variable in the else branch.

I tried different compiler options and a different compiler (clang 4.0.1 vs. 5.0.1), apparently there is really something fishy in my code. Any thoughts?

Aucun commentaire:

Enregistrer un commentaire