shared_ptr and covariant return types

In this post Peter Dimov shows a solution for the covariant return type problem when using shared_ptr: http://lists.boost.org/boost-users/2003/02/2996.php I'm interested in the free function solution he provides:
[snip] you can use the usual pattern from the no-covariant-return days:
class B { virtual shared_ptr<B> do_clone() const = 0; };
class X: public B { virtual shared_ptr<B> do_clone() const { return shared_ptr<X>(new X(*this)); }
public:
shared_ptr<X> clone() const { shared_ptr<X> px = dynamic_pointer_cast<X>(this->do_clone()); assert(px); return px; } };
It buys you some extra safety, too.
You could also use a free function:
template<class X> shared_ptr<X> clone(X const & x) {
shared_ptr<X> px = dynamic_pointer_cast<X>(x.do_clone()); assert(px); return px; }
So, to clone an object using the clone method, I could use: X* x; shared_ptr<X> spX(x = new X()); shared_ptr<X> spX2 = spX->clone(); // or: shared_ptr<X> spX3 = x->clone(); But how is the free function meant to be used? This provokes the compiler error: '... do_clone() const is private ...': shared_ptr<X> spX4 = clone(*spX); Thank you Bernhard

Hi! do_clone is really private ;) Your derived class has public clone member and you should use it from the free function, but no the do_clone. Regards, Ovanes On 8 Nov 2007 14:53:49 +0100, Bernhard Wagner boost < lists.boost.org@xmlizer.biz> wrote:
In this post Peter Dimov shows a solution for the covariant return type problem when using shared_ptr: http://lists.boost.org/boost-users/2003/02/2996.php
I'm interested in the free function solution he provides:
[snip] you can use the usual pattern from the no-covariant-return days:
class B { virtual shared_ptr<B> do_clone() const = 0; };
class X: public B { virtual shared_ptr<B> do_clone() const { return shared_ptr<X>(new X(*this)); }
public:
shared_ptr<X> clone() const { shared_ptr<X> px = dynamic_pointer_cast<X>(this->do_clone()); assert(px); return px; } };
It buys you some extra safety, too.
You could also use a free function:
template<class X> shared_ptr<X> clone(X const & x) {
shared_ptr<X> px = dynamic_pointer_cast<X>(x.do_clone()); assert(px); return px; }
So, to clone an object using the clone method, I could use:
X* x; shared_ptr<X> spX(x = new X()); shared_ptr<X> spX2 = spX->clone(); // or: shared_ptr<X> spX3 = x->clone();
But how is the free function meant to be used?
This provokes the compiler error: '... do_clone() const is private ...': shared_ptr<X> spX4 = clone(*spX);
Thank you Bernhard
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
participants (2)
-
Bernhard Wagner boost
-
Ovanes Markarian