安置回去在原地施工失败

Emplace back fails at in place construction

本文关键字:原地 施工 失败      更新时间:2023-10-16

>我有一个对象,我想只构造一次,因为它所在的类通过向对象添加原始指针来跟踪它的对象。不过,内联构造它似乎失败了:

// Defined utilities:
ModuleClusterPlot(Type typeArg, const int& layer, const int& module, const int& ladder, const int& startEventArg, const int& endEventArg);
~ModuleClusterPlot();
// Invalid utilities
ModuleClusterPlot(ModuleClusterPlot& t_other) = delete;
ModuleClusterPlot(ModuleClusterPlot&& t_other) = delete;
ModuleClusterPlot& operator=(const ModuleClusterPlot& t_other) = delete;
ModuleClusterPlot& operator=(ModuleClusterPlot&& t_other) = delete;

通过 emplace back 调用构造函数失败,因为它尝试调用移动构造函数(为什么?

moduleClusterPlots.emplace_back(t_type, t_layer, t_module, t_ladder, i, i);

我在这里做错了什么?我正在使用gcc 7.1.0std=c++14标志。

最小示例:

#include <vector>
class ModuleClusterPlot
{
public:
enum Type
{
foo = 0,
bar
};
ModuleClusterPlot(Type typeArg);
~ModuleClusterPlot();
// Invalid utilities
ModuleClusterPlot(ModuleClusterPlot& t_other) = delete;
ModuleClusterPlot(ModuleClusterPlot&& t_other) = delete;
ModuleClusterPlot& operator=(const ModuleClusterPlot& t_other) = delete;
ModuleClusterPlot& operator=(ModuleClusterPlot&& t_other) = delete;
};
int main()
{
std::vector<ModuleClusterPlot> collection;
collection.emplace_back(ModuleClusterPlot::foo);
}

如何防止在此处调用移动构造函数?

std::vector<T>::emplace_back需要移动构造函数或复制构造函数。 原因是它可能需要重新分配内存并将现有对象移动/复制到新的缓冲区中。

即使您只在空向量上调用它,实际上不需要移动任何现有对象,请记住,相同的函数emplace_back可以在空向量和非空向量上使用。 该函数不可能只知道它是否从空状态使用,因此当实例化成员函数时,处理非空向量的代码也必须有效。

您违反了emaplce_back的约束。 如果我们查看 [sequence.reqmts] 中的表 101,我们会得到

要求:T 应从参数构造到 X 中。对于向量,T 也应可移动到 X 中。

强调我的

由于您的类不可移动插入,因此它不适用于emplace_back

之所以需要这样做,是因为size()大于capacity(),那么向量需要分配新的存储并将元素移动到该新存储。 如果它不能做到这一点,那么向量就不能按预期运行。