-2

I pass an Image object to my hash table with the method insert().

htImages.insert(WALL_UP_CLOSE, imgWalls[WALL_UP_CLOSE]);

As you can see, I'm passing the object into Value by reference.

void insert(const Key &key, const Value &value)
{
    Entry entry;
    int index;

    // Build up entry structure
    entry.m_key = key;
    entry.m_value = value;

    // Build the insertion index
    index = m_hash(key) % m_size;

    // Insert the value
    m_table[index].append(entry);

    m_count++;
}

However, once this function ends at the last line, the destructor below is being called.

Image::~Image()
{
    glDeleteTextures(1, &m_handle);
    refCount--;
}

My preference is that the destructor is not called. I'm passing it by reference, so why is the destructor being called?

Phil
  • 607
  • 1
  • 8
  • 22

1 Answers1

3

You have a local variable of type Entry, which is automatically destroyed at the end of the function.

When it is destroyed, destructors run for each of its subobjects.

Probably entry.m_value = value; is copying something, and the extra copy needs to be cleaned up.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Thanks for spotting this simple issue out. Giving Entry a static modifier solved the issue. – Phil Jan 17 '15 at 21:51
  • @Phil: I somehow doubt that really fixes it. As I already said, `entry.m_value = value;` looks like a copy assignment operator. Where does that copy go? – Ben Voigt Jan 17 '15 at 21:52