【发布时间】: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:将声明放在问题中的代码区域中,
*和&不会被咕噜吃掉。
标签: c++ c++11 stdvector move-semantics reference-counting