未调用 C++ vector 元素构造函数

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

<分区>

我有一个带有复制构造函数和 move 构造函数的类,它们都向标准输出报告消息,直到我弄清楚这个问题。将本地对象插入 vector 时,不会调用任何构造函数,从而导致以后出现问题。但是,当我使用 std::move 告诉它使用 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

这让我很困惑。

最佳答案

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 A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments

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

关于未调用 C++ vector 元素构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17936009/

相关文章:

c++ - 什么是智能指针,我应该什么时候使用它?

c++ - C++11 中的 auto 关键字奇怪行为

c++ - 在泛型函数中使用仿函数

c++ - 在 hackerrank 生日蛋糕蜡烛问题中使用 std::vector

c++ - glPolygonMode 未以正确模式呈现

c++ - 使用 sizeof 在 C++ 中得到不同的结果

c++ - 就地 union 排序 vector

c++ - 如何重载自定义 std::sort 比较函数?

C++:未定义对命名空间中函数的引用

C++迭代器到集合的最后一个元素