【问题标题】:Why is the destructor called when the object is passed by reference?为什么引用传递对象时要调用析构函数?
【发布时间】:2015-01-18 05:36:36
【问题描述】:

我使用 insert() 方法将一个 Image 对象传递给我的哈希表。

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

如您所见,我通过引用将对象传递给 Value。

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++;
}

然而,一旦这个函数在最后一行结束,下面的析构函数就会被调用。

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

我的偏好是不调用析构函数。我是通过引用传递的,为什么要调用析构函数呢?

【问题讨论】:

  • 怎么样你通过了吗?向我们展示代码。事实上,所有相关的代码。
  • Image 与第一个代码示例有什么关系?
  • 显示Entry的定义,m_table的类型,以及调用该函数的代码。
  • 您正在创建KeyValue 子对象以及entry
  • 嗯,这是我列出的我们需要看到的三件事之一。

标签: c++


【解决方案1】:

你有一个Entry 类型的局部变量,它在函数结束时被自动销毁。

当它被销毁时,析构函数会为其每个子对象运行。

可能entry.m_value = value; 正在复制某些内容,需要清理多余的副本。

【讨论】:

  • 感谢您发现这个简单的问题。给 Entry 一个静态修饰符解决了这个问题。
  • @Phil:我怀疑这是否真的能解决问题。正如我已经说过的,entry.m_value = value; 看起来像一个复制赋值运算符。那个副本去哪儿了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-10
  • 2019-11-16
  • 2019-01-29
  • 2018-05-24
  • 1970-01-01
  • 2014-06-13
相关资源
最近更新 更多