【问题标题】:C++ Vector element constructor not called [duplicate]C ++向量元素构造函数未调用[重复]
【发布时间】:2013-07-29 22:47:34
【问题描述】:

我有一个带有复制构造函数和移动构造函数的类,它们都向标准输出报告消息,直到我解决了这个问题。将本地对象推送到向量上时,不会调用构造函数,这会导致以后出现问题。但是,当我使用 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

这让我很困惑。

【问题讨论】:

  • 保留做什么,这就是你的两个函数之间的差异
  • 你的问题是关于向量,但我没有看到。
  • 向量上的 push_back 是否有可能逐个成员分配?如,它调用 operator=() 而不是复制构造函数?
  • @Daggerbot:将声明放在问题中的代码区域中,*&amp; 不会被咕噜吃掉。

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


【解决方案1】:
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&、const X&、volatile X& 或 const volatile X& 类型,并且没有其他参数否则所有其他参数都有默认参数

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

【讨论】:

  • 刚刚也意识到了这一点。但是,让我们从现有的十几个问题中找出一个,好吗?
  • 这确实是问题所在。固定的! :D
猜你喜欢
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2018-10-17
  • 2012-02-06
相关资源
最近更新 更多