gpt4 book ai didi

c++ - 删除复制构造函数/赋值会破坏标准库操作

转载 作者:行者123 更新时间:2023-11-28 00:00:35 24 4
gpt4 key购买 nike

我有几个类要求它们的实例在运行时不能有相似的拷贝。假设其中一个类看起来像 -

class A{
int id;
int printerNum;

bool failState = true;
//....

public:
//....

};

现在 idprinterNum 必须对每个实例都是唯一的,因为没有两个实例可以同时控制同一台打印机。 id 仅在对象构造时生成,但 printerNum 可以更改。对于这两个要求,我在构造函数和 failState 变量中提供了检查,它永远不会正确初始化对象并在发生错误时将 failState 设置为 true。

我还考虑删除复制构造函数和赋值运算符,以确保用户永远不会创建拷贝,并且只能从构造函数初始化它,以便 id 和 printerNum 保持唯一。

但在进行此更改之前,我想问一下,这会破坏标准命名空间内可用的其他算法和容器吗?他们可能经常使用赋值运算符和复制构造函数,如果我像这样明确删除它们会发生什么 -

// no copy
A(const A&) = delete;

// no assign
A& operator=(const A&) = delete;

如果不可能,或者有其他方法可以做到这一点,我会欢迎所有建议。谢谢 :)

最佳答案

在 C++11 中,对容器中使用的类型的要求取决于您调用的操作。他们唯一无条件要求的是类型是 Erasable,当与标准分配器一起使用时,它等同于要求 p->~T() 是 well-形成并有效。

因此,在重新分配 vector 或使用 insert 的复制构造版本时,需要复制构造。例如,在 vector 中间插入元素或对容器进行排序时需要赋值。

例如,这里引用自 http://en.cppreference.com/w/cpp/container/vector vector 上:

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements.

关于c++ - 删除复制构造函数/赋值会破坏标准库操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39372305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com