I am interested in whether it is possible to replicate the behaviour of the virtual constructor pattern (e.g. see virtual constructor example) using std::shared_ptr. The straightforward approach of replacing the raw pointers by shared pointers fails for somewhat obvious reasons (invalid covariant return type). I am interested if anyone knows of any alternatives that would support smart pointers.
Smart pointers are used everywhere in the project and the virtual constructor-like approach seems like the only approach possible for the problem I am currently working on...
I am not sure if the code is necessary, as it can be found in the link above, but, just in case:
class A
{
public:
virtual std::shared_ptr<A> clone(void) const = 0;
virtual void mymethod() const = 0;
};
class B : public A
{
std::shared_ptr<B> clone(void) const
{
return (new B(*this));
}
void mymethod() const
{
std::cout << "type something";
}
};
class C
{
public:
void mymethod(std::shared_ptr<A const> MyB)
{
std::shared_ptr<A const> MyB2 = MyB -> clone();
MyB2 -> mymethod();
}
};
Aucun commentaire:
Enregistrer un commentaire