I heave roughly speaking the following hierarchy
class Base {
public:
virtual int value() const = 0;
};
class Derived1 : public Base {
public:
int value() const {
return 1;
}
};
class Derived2 : public Base {
public:
int value() const {
return -1;
}
};
class Derived3 : public Base {
public:
Derived3(const Base & underlying);
int value() const {
return underlying_.value() + 10;
}
private:
const Base & underlying_;
};
Derived3::Derived3(const Base & underlying)
:underlying_(underlying) {}
There is also a singleton holder for Base objects. One branch of the workflow goes something like this:
1) Get a Derived1 object out of the holder
2) Instantiate a Derived3 object using the Derived1 object and use it.
I’m in a multithreaded environment and am worried about the problem of the underlying_ reference_ becoming invalidated during the lifetime of the second object. I am not an expert on multithreading but I believe this can happen.
I would like for Derived2 objects to own a copy of the underlying object but because Base is abstract I cant do that. Can someone comment of this design and suggest a different approach.
To add, there are two driving thoughts behind the above design. Derived3 should be though of as a shift of Base type objects. One desire is to have shifts of shifts. Another desire is to be able to store Derived3 objects in the singleton for possible use later.
You can try to ‘clone’ your classes. I mean, each derived class may clone itself and use this clone in others derived.
With this solution, you can hold new Derived all time you need. Don’t forget to delete it. Your factory returns a Base object that can be cloned to obtain a new one.