我有一個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