未调用C++矢量元素构造函数

C++ Vector element constructor not called

本文关键字:元素 构造函数 调用 C++      更新时间:2023-10-16

我有一个带有复制构造函数和移动构造函数的类,它们都向stdout报告消息,直到我解决这个问题。当将局部对象推送到向量上时,永远不会调用构造函数,这会导致以后的问题。然而,当我使用std::move告诉它使用move构造函数而不是copy构造函数时,一切都很好。这是一个错误,还是我误解了std::vector的操作方式?

这些是我的对象的构造函数:

template <typename R>
inline Ref (const Ref<R> &other)
: m_ptr(other.m_ptr)
{
  LogDebugc("copy ctor ", long(other.m_ptr));
  Retain(m_ptr);
}
template <typename R>
inline Ref (Ref<R> &&other)
: m_ptr(other.m_ptr)
{
  LogDebugc("move ctor ", long(other.m_ptr));
  other.m_ptr = nullptr;
}

问题出现在这里:

void SetState (State *state)
{
  // Keep a reference so we don't free the state by mistake
  Ref<State> ref (state);
  s_stateStack.clear();
  if (ref) {
    LogDebugc("pre push ", long(state));
    s_stateStack.push_back(ref);
    LogDebugc("post push ", long(state));
  }
}

我期待得到输出。。。

[dbg] pre push 6415744
[dbg] copy ctor 6415744
[dbg] post push 6415744

但相反,我得到了。。。

[dbg] pre push 6415744
[dbg] post push 6415744

当我更改状态被推回的行时,我得到:

s_stateStack.push_back(std::move(ref));
[dbg] pre push 6415744
[dbg] move ctor 6415744
[dbg] post push 6415744

这让我非常困惑。

template <typename R>
inline Ref (const Ref<R> &other)
: m_ptr(other.m_ptr)
{
  LogDebugc("copy ctor ", long(other.m_ptr));
  Retain(m_ptr);
}

这不是一个复制构造函数。因此,它没有被调用。

§12.8如果类X的非模板构造函数的第一个参数是类型X&,则该构造函数是复制构造函数;,常量X&,易失性X&或常数易失性X&,并且要么没有其他参数,要么所有其他参数都有默认参数

编译器使用隐式生成的复制构造函数,而不是您编写的转换构造函数。

相关文章: