首页 > 解决方案 > 具有 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 *>>

注意:在参数化构造函数中,我只是浅拷贝,因为我可以。不过,这不适用于复制构造函数。

提前致谢。

标签: c++constantscopy-constructor

解决方案


最简单的解决方案是创建一个辅助函数,它接受 aconst std::vector<Customer *>并返回作为std::vector<Customer *>参数的深层副本的 a。然后,在构造函数的初始化列表中,使用该函数来初始化您的私有成员。

或者,如果您想限制对它的访问,该辅助函数可以是您的类private的成员。static这在构造函数或其初始化列表中是可以接受的,因为static成员函数不依赖于正在初始化的类的非静态成员,因此不依赖于已完成的构造函数。

如果在制作深拷贝的辅助函数中出现问题,辅助函数将需要适当地清理(例如,如果其中一个Customer对象的构造失败,则需要释放任何成功构造的对象以避免内存泄漏)。


推荐阅读