Quote:Fair point!
But "copy the thing that is pointed to" pointers alone won't be enough for that to work in general, you'd need a standard polymorphic clone of some sort, or a special container, or a number of other extra enhancements.
Im not sure what you mean by a special container but it should be fairly easy, for example, consider the following (naive) minimal implementation.
// this version provides fast acess to the stored ptr at the cost of slightly// more memory usage, it is however possible to reduce memory usage by// adding another layer of indirection when accessing the stored ptr// used to maintain type information for copyingtemplate<typename BaseType>struct copy_ptr_storage{ virtual BaseType* copy(BaseType*) = 0; virtual copy_ptr_storage<BaseType>* clone() = 0;};// stores the actual type infotemplate<typename BaseType, typename T>struct copy_ptr_impl : copy_ptr_storage{ BaseType* copy(BaseType* p) { return new new T(*static_cast<T*>(p)); } copy_ptr_storage<BaseType>* clone() { return new copy_ptr_impl<BaseType, T>(); }};// the ptrstruct copy_ptr<typename BaseType>{ template<typename T> copy_ptr(T* ptr): type_ptr(new copy_ptr_impl<T>()), base_ptr(ptr) { } copy_ptr(const copy_ptr<BaseType>& rhs): type_ptr(rhs.type_ptr->clone()), base_ptr(rhs.type_ptr->copy(rhs.base_ptr)); { } copy_ptr<BaseType&> operator=(const copy_ptr<BaseType>& rhs) { delete base_ptr; base_ptr = rhs.type_ptr->copy(rhs.base_ptr); delete type_ptr; type_ptr = rhs.type_ptr->clone(); } BasePtr& operator*() { return *base_ptr; } BaseType* oprator->() { return base_ptr; } ~copy_ptr() { delete type_ptr; delete base_ptr; }private: copy_ptr_storage* type_ptr; BaseType* base_ptr;};
With a little bit of work you can also get rid of the extra dynamic allocations for type_ptr.
On second thought that probally counts as the "stand alone polymorphic clone" that you mentioned but atleast the client doesnt need to know about it, as far as theyre concerned it "just works"
Edit:
Quote:Original post by Zahlman
Quote:Original post by jpetrie
Perhaps I'm misunderstanding the functionality you want, but why not just use a non-pointer if you need operator= to "copy the thing?"
Polymorphism, Pimpls, virtual clone idiom etc. (If you can standardize the name of the clone() function, it should be possible to use SFINAE introspection to make use of it?)
As i just demonstrated you can use the already standardized version, a copy constructor, using a clone detected with sfinae places more requirments on the user and (with some changes to my example, i.e. get rid of memory overhead and dynamic allocations) wouldnt be anymore effecient or usefull as both would require a single virtual function call...