未调用C++矢量元素构造函数
C++ Vector element constructor not called
我有一个带有复制构造函数和移动构造函数的类,它们都向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&,并且要么没有其他参数,要么所有其他参数都有默认参数
编译器使用隐式生成的复制构造函数,而不是您编写的转换构造函数。
相关文章:
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 如何在 c++ 中将整个数组初始化为类构造函数中的单个元素
- 无法在构造函数中执行设置元素插入
- 如何在构造函数初始值设定项列表中使用 n 个元素初始化 std::vector<std::time_t>
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- std::tuple默认构造函数,带有move可构造元素
- 如果我想从类型"T"定义元素的容器(来自 STL),那么"T"必须使用默认构造函数?
- 为 unordered_map 中的元素设置默认构造函数(如果是 [] 运算符)
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 为什么只有在向量中已经有一个元素时才调用移动构造函数?
- 我们如何使用下面的集合构造函数构造设置元素
- clang格式:如何将构造函数的初始值设定项列表的每个元素保存在单独的行上
- 在不调用构造函数的情况下创建 Vector 元素
- C2280 STD :: vector的默认构造函数尽管具有移动构造函数,但仍需要元素的复制构造函数
- 实例化 std::vector 的唯一元素,而无需复制构造函数
- 如何将参数传递给工厂元素构造函数
- 未调用C++矢量元素构造函数
- vector.resize()方法在调整大小时调用默认的元素构造函数
- 在类构造函数中设置std::vector,为元素构造函数设置不同的值