简体   繁体   中英

C++ map insertion

// Create sound effect
SoundEffect* newSoundEffect = new SoundEffect(frequencyArray);

if (soundEffects.find(name) == soundEffects.end())
    soundEffects[name] = (*newSoundEffect);

// Clean up memory
delete [] frequencyArray;
delete newSoundEffect;

frequencyArray (above) and m_data (below) are dynamically allocated. soundEffects is a std::map . Whenever I try to insert the value pointed to by newSoundEffect into soundEffects , the destructor of SoundEffect is triggered, and for some reason, when the destructor tries to delete m_data , I get the error "Access violation reading location 0xCCCCCCCC. I read somewhere that this location denotes uninitialized memory or something. But in the code snippet above, using Visual Studio's debugger, I can confirm that m_data in newSoundEffect pointing to a valid memory sequence. What am I doing wrong?

~SoundEffect()
{
    if (m_data != NULL)
        delete [] m_data; // Error :(
}

EDIT : Owing to @Chad's suggestion, I went ahead and added a copy constructor to the SoundEffect class, but it hasn't helped, because although newSoundEffect is definitely constructed when I try to put it into soundEffects , the copy constructor receives an object with uninitialized member variables; an uninitialized SoundEffect .

Your SoundEffect class will need a copy constructor and copy assignment operator to be used in this manner.

Read this: The rule of three

Need to see the constructor.

But 0xCCCCCCCC in microsoft world means it has not been allocated.

Short answer: Implement a copy constructor to copy the bytes of m_data appropriately (by reallocating a new buffer, and appropriately copying the bytes).

Another answer: Make your map a map of SoundEffect* (pointers) instead of SoundEffect instances. Don't delete newSoundEffect after inserting it into the map.

soundEffects[name] = (*newSoundEffect); is trying to put a copy of the SoundEffect object into the map.

I'm pretty sure you just want to store a SoundEffect* as the map value, instead of a SoundEffect object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM