C++ 复制具有常量向量成员的类的构造函数
我的代码中有类C++ 复制具有常量向量成员的类的构造函数,c++,constants,copy-constructor,C++,Constants,Copy Constructor,我的代码中有类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 *>
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
,所以我不能向它添加元素
我得到以下错误:
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 *>>
没有重载函数“std::vector::push_back”的实例
[with _Tp=Customer*,_Alloc=std::allocator]”匹配
参数列表和对象(对象具有阻止
匹配)--参数类型为:(Customer*)--对象类型为:const
向量
注意:在参数化构造函数中,我只是浅复制,因为我可以。但是,这对复制构造函数不起作用
提前感谢。您需要一些类似的东西来作为成员初始化器的一部分进行复制
auto copy_iter(auto iter)
{
return boost::make_transform_iterator(iter, [](Customer * c){ return c->copy(); });
}
OpenTable::OpenTable(const OpenTable& other)
: tableId(other.tableId),
customers(copy_iter(other.customers.begin()), copy_iter(other.customers.end()))
{}
或者交替地
OpenTable::OpenTable(const OpenTable& other)
: tableId(other.tableId),
customers(boost::copy_range<std::vector<Customer *>>(other.customers | boost::adaptors::transformed([](Customer * c){ return c->copy(); })))
{}
OpenTable::OpenTable(const OpenTable和其他)
:tableId(其他.tableId),
客户(boost::copy_range(other.customers | boost::adapters::transformed([](客户*c){return c->copy();})))
{}
为什么要使用常量类成员?你对他们无能为力。将公共访问功能改为只读
std::vector<Customers *> const getCustumers() const { return customers;}
int const getTableId() const { return tableId; }
std::vector const getCustumers()const{return customers;}
int const getTableId()const{return tableId;}
这将为您提供一个只读的客户向量或一个无法修改的表id。复制构造函数没有问题。最简单的解决方案是创建一个helper函数,该函数接受
const std::vector
,并返回一个std::vector
,它是参数的深度副本。然后,在构造函数的初始化器列表中,使用该函数初始化私有成员
或者,如果您想限制对该助手函数的访问,则该助手函数可以是类的私有
和静态
成员。这在构造函数或其初始化器列表中是可以接受的,因为静态
成员函数不依赖于初始化的类的非静态成员,因此不依赖于已完成初始化的构造函数
如果制作深度复制的助手函数出现问题,助手函数将需要适当清理(例如,如果一个
Customer
对象的构造失败,则需要释放任何成功构造的对象以避免内存泄漏)。是否Customer
是多态基类?如果没有,为什么需要指针?如果您需要指针,您是否考虑过所有权语义,或者与?const
数据成员共享Customer
对象的所有权几乎是不值得的。创建一个helper函数(如果要限制对类的访问,可以是类的private
和static
成员)它接受一个const std::vector
,并返回一个深度副本std::vector
。然后,在构造函数的初始化器列表中,使用它初始化您的私有成员。@BarakB调用一个不依赖(尚未初始化)的非虚拟成员是可以的成员数据。static
成员很容易满足这些标准。另外,将指针更改为std::unique_ptr
将更容易为类提供异常保证。
std::vector<Customers *> const getCustumers() const { return customers;}
int const getTableId() const { return tableId; }