Search code examples
c++shared-ptr

C++ make::shared wrapping on existing raw pointer


I am working on a small wrapper for an FMOD library. Below is a snippet of the code that I have, and there are other libraries that manage the SoundData class:

class SoundData
{
public: 
    ...
    std::string mSoundName;
    std::shared_ptr<FMOD::Sound> mFmodSoundHandle;
    ...
}

void SoundLib::CreateSound(SoundData& data)
{
    FMOD::Sound *sound = nullptr;
    system->createSound(data.mSoundName.data(), FMOD_DEFAULT, nullptr, &sound);
    data.mFmodSoundHandle = std::make_shared<FMOD::Sound>(sound);
}

Trying to compile this snippet of the code, I get this error:

Error C2664 'FMOD::Sound::Sound(const FMOD::Sound &)': cannot convert argument 1 from 'FMOD::Sound *' to 'const FMOD::Sound &' SoundLib ...\MSVC\14.29.30133\include\xutility 158

I cannot quite understand if I am using std::make_shared() in the wrong way here? The goal here is to save the output from createSound() that is passed as a sound variable into the structure SoundData. Variable data will be managed afterwards.


Solution

  • You're passing a pointer where you should pass a reference. Try *sound.

    Notice that you're not wrapping a pointer, you're creating a new instance of Sound and copying the value of *sound into it.

    To wrap it consider:

    data.mFmodSoundHandle.reset(sound);