c++ - 具有 const 向量成员的类的复制构造函数
问题描述
我的代码中有这个类OpenTable
:
class OpenTable : public BaseAction {
public:
OpenTable(int id, std::vector<Customer *> &customersList);
OpenTable(const OpenTable& other);
private:
const int tableId;
const std::vector<Customer *> customers;
};
我需要为这个类实现一个复制构造函数(我知道这可能是一个糟糕的设计,但我被指示这样做)。我在尝试深度复制 const vector 时遇到了问题customers
。
我尝试了以下方法:
OpenTable::OpenTable(const OpenTable& other): tableId(other.tableId)
{
for(std::vector<Customer*>::const_iterator i=other.customers.begin(); i!=other.customers.end(); i++) {
customers.push_back((*i)->copy()); // copy returns a Customer*
}
但显然它没有编译,可能是因为向量是const
,因此我不能向它添加元素。
我收到以下错误:
no instance of overloaded function "std::vector<_Tp, _Alloc>::push_back
[with _Tp=Customer *, _Alloc=std::allocator<Customer *>]" matches the
argument list and object (the object has type qualifiers that prevent a
match) -- argument types are: (Customer *) -- object type is: const
std::vector<Customer *, std::allocator<Customer *>>
注意:在参数化构造函数中,我只是浅拷贝,因为我可以。不过,这不适用于复制构造函数。
提前致谢。
解决方案
最简单的解决方案是创建一个辅助函数,它接受 aconst std::vector<Customer *>
并返回作为std::vector<Customer *>
参数的深层副本的 a。然后,在构造函数的初始化列表中,使用该函数来初始化您的私有成员。
或者,如果您想限制对它的访问,该辅助函数可以是您的类private
的成员。static
这在构造函数或其初始化列表中是可以接受的,因为static
成员函数不依赖于正在初始化的类的非静态成员,因此不依赖于已完成的构造函数。
如果在制作深拷贝的辅助函数中出现问题,辅助函数将需要适当地清理(例如,如果其中一个Customer
对象的构造失败,则需要释放任何成功构造的对象以避免内存泄漏)。
推荐阅读
- reactjs - '(id: any, title: any, body: any, image: any) => Element' 类型的参数不能分配给类型参数
- azure - 如何使用 Azure 门户或 PowerShell 将服务主体设置为应用程序注册所有者?
- c - 缓冲区溢出攻击,不执行shellcode
- javascript - useEffect 仅运行一次,刷新后不再获取
- flutter - 未找到“cloud_firestore”
- vuejs3 - 使用VUE 3的SSR项目,express和使用vue/head
- database-design - 在注册表中存储问题的最佳方法
- node.js - 从博客(MongoDB NodeJs)创建相关标签网络
- cloud - Talend Cloud 创建集群
- oracle - Oracle ORA-00904 错误:标识符无效