我有一个Data
类和一个Wrapper
类,它提供访问Data
的方法。 WrapperMutable
类扩展Wrapper
添加方法来修改Data
。通过扩展添加可变性
#include <memory>
using namespace std;
class Data {
public:
void update(); // non-const method which modifies internal state of Data
};
class Wrapper
{
public:
Wrapper(shared_ptr<Data const> data) : myData(data) {} // accepts const pointer
// ...bunch of functions providing read-only access to aspects of the Data...
protected:
shared_ptr<Data const> myData; // stores const pointer
};
// Extend Wrapper with methods to modify the wrapped Data.
class WrapperMutable : public Wrapper
{
public:
WrapperMutable(shared_ptr<Data> data) : Wrapper(data) {}
// ERROR: invoking non-const method on const object:
void updateData() { myData->update(); }
};
当然,问题是与const
-ness包裹Data
对象的,这意味着WrapperMutable
不能修改它。
我认为改变Wrapper
接受和储存非const
Data
,但通常是客户本身将只需要const Data
访问,所以那么他们将被迫const_cast
或以创造一个Wrapper
复制。
所以我已经能够实现这一目标的唯一途径是通过保持一个附加的非const
指针在WrapperMutable
类,并使用该在可变背景:
class WrapperMutable : public Wrapper
{
public:
WrapperMutable(shared_ptr<Data> data) : Wrapper(data), myMutableData(data) {}
// Use myMutableData instead of the const myData
void updateData() { myMutableData->update(); }
private:
shared_ptr<Data> myMutableData; // non-const pointer to the same Data as in Wrapper
};
有没有更好的办法?显然,从Wrapper
得到WrapperMutable
是我的问题的来源,但我不想在WrapperMutable
中重写所有Wrapper
的方法。
你就不能更改'shared_ptr的 myData'到'常量的shared_ptr myData'?这也允许定义'Wrapper(Data * const data):myData(data){}' –
“,但客户端本身通常只能访问'const Data'” - 我认为这是导致问题。如果他们不能修改数据,那么也不应该将该数据传递给任何可以修改它的人。 – Petr
@SimonKraemer我认为这仍然会强制客户端持有指向'const Data'的指针来执行'const_cast',不是吗? – atkins