Boost logo

Boost Users :

From: John (john_at_[hidden])
Date: 2008-06-24 11:21:23


Thorsten Ottosen wrote:
> John skrev:
>> This pattern/idiom is well-established:
>>
>> struct A {
>> virtual A* clone () = 0;
>> };
>>
>> struct B : public A {
>> virtual B* clone ();
>> };
>>
>>
>> But the above does not work when the pointers A* and B* are replaced
>> by shared_ptr<A> and shared_ptr<B>:
>>
>> struct A {
>> virtual shared_ptr<A> clone () = 0;
>> };
>>
>> struct B : public A {
>> virtual shared_ptr<B> clone ();
>> };
>>
>>
>> Is there a workaround? Another way to solve the same problem? Thanks!
>
> Well, don't use shared_ptr here. A newly created clone is not shared,
> and it makes the interface less usable in other context to return a
> shared ptr here.
>
> -Thorsten

Hah! Well, yes, I guess it's true that there's always an option not to use smart
pointers at all. :) Perhaps people will make too many assumptions about the
method based on the name, "clone". Instead, pretend the clone() method is named
something else, without any other assumptions.

For example, pretend it's a get_row() method for a database cursor abstraction.
The method might trigger a fetch, in which case the returned object is not
shared, or it might return a previously fecthed row. Also, whether this method
is usable in non-smart-pointer context is not a concern. -John


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net