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

时间:2013-07-29 23:36:50

标签: c++ c++11 stdvector move-semantics reference-counting

我有一个带有复制构造函数和移动构造函数的类,它们都向stdout报告消息,直到我发现这个问题为止。将本地对象推送到向量时,不会调用任何构造函数,从而导致以后出现问题。但是,当我使用std :: move告诉它使用移动构造函数而不是复制构造函数时,一切正常。这是一个错误,还是我误解了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

这让我很困惑。

1 个答案:

答案 0 :(得分:0)

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&amp;,const X&amp;,volatile X&amp; X,则X类的非模板构造函数是一个复制构造函数。或const volatile X&amp;,并且没有其他参数,或者所有其他参数都有默认参数

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