安置回去在原地施工失败
Emplace back fails at in place construction
>我有一个对象,我想只构造一次,因为它所在的类通过向对象添加原始指针来跟踪它的对象。不过,内联构造它似乎失败了:
// 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.0
std=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()
,那么向量需要分配新的存储并将元素移动到该新存储。 如果它不能做到这一点,那么向量就不能按预期运行。
相关文章:
- 为什么 boost::interprocess::managed_shared_memory 在施工时会抛出 boost
- 施工期间的虚函数调用
- 施工后立即在向量上调用清晰?
- 安置回去在原地施工失败
- 施工中的自我参考
- 高效的施工委托
- C GRPC ::完整的施工速度约为14K
- 减少将临时对象分配给现场施工
- C 在施工中定义的容器
- 过度施工
- 在施工时预留的标准集装箱?
- 延期构件施工
- 超载*操作员只能与一个施工人员一起工作
- 如何在工厂设计中支持多个施工签名
- std::lock_guard<std::mutex> 施工上的段错误?
- 班级组成及施工顺序
- 委派施工人员
- Cin和施工方案
- 施工期间的非恒定发电机单程初始化
- 强制"in-place"施工