I also had same question, but my aim was to use standard QT classes like QSharedData and QExplicitlySharedDataPointer ... solution I came upon is (small sample):
class BaseClass{
public:
BaseClass(){
_d = new BaseData();
}
protected:
BaseData(BaseData *data){
_d = data;
}
QExplicitlySharedDataPointer<BaseData> _d;
};
class DerivedClass : public BaseClass{
public:
DerivedClass() : BaseClass(new DerivedData()){
_d = static_cast<DerivedData*>(BaseClass::_d.data());
}
// Construtor for upcasting. This must be implemented if we want to do upcasting with variables placed in stack.
DerivedClass(BaseClass &bs) : BaseClass(bs){
_d = static_cast<DerivedData*>(BaseClass::_d.data());
}
protected:
QExplicitlySharedDataPointer<DerivedData> _d;
};
main(){
DerivedClass dc;
BaseClass bs = dc;
DerivedClass dc2 = bs;
DerivedClass dc3 = static_cast<DerivedClass>(bs); // Same result as above
// After all these operations we have only single instance of shared data
}
class BaseClass{
public:
BaseClass(){
_d = new BaseData();
}
protected:
BaseData(BaseData *data){
_d = data;
}
QExplicitlySharedDataPointer<BaseData> _d;
};
class DerivedClass : public BaseClass{
public:
DerivedClass() : BaseClass(new DerivedData()){
_d = static_cast<DerivedData*>(BaseClass::_d.data());
}
// Construtor for upcasting. This must be implemented if we want to do upcasting with variables placed in stack.
DerivedClass(BaseClass &bs) : BaseClass(bs){
_d = static_cast<DerivedData*>(BaseClass::_d.data());
}
protected:
QExplicitlySharedDataPointer<DerivedData> _d;
};
main(){
DerivedClass dc;
BaseClass bs = dc;
DerivedClass dc2 = bs;
DerivedClass dc3 = static_cast<DerivedClass>(bs); // Same result as above
// After all these operations we have only single instance of shared data
}
To copy to clipboard, switch view to plain text mode
The result is that both base class and derived class has separate explicitly shared pointers named "_d". But its impossible to avoid this!!! The best you can achieve here is variable overloading. But this pointer points to the same data class instance!!! If somebody will find better solution, it would be interesting to hear it.
P.S. after posting this I just thought that it is also possible not to define variable "_d" in derived class but use BaseClass variable instead. Just in this case well have to do more casting operations when accesing values.
Bookmarks