c++ - Cast a polymorphic smart pointer object -


i implemented following smart pointer template class:

#ifndef __projectmanager__msharedptr__ #define __projectmanager__msharedptr__  #include <stdio.h> #include "refcount.h"  template <class t> class msmartptr {      t *data;     refcount *rc;  public:      msmartptr(t* srcptr);     msmartptr(const msmartptr&);     ~msmartptr();     t* operator->() const;     t& operator*() const;     msmartptr<t>& operator=( msmartptr&);     msmartptr<t> operator()(msmartptr&); };  template<class t> msmartptr<t> msmartptr<t>::operator()(msmartptr<t>& src) {     return dynamic_cast<??>(src); }  template <class t> msmartptr<t>::msmartptr(t *srcptr): data(srcptr) {     rc = new refcount();     rc->add(); }  template<class t> msmartptr<t>::~msmartptr() {     if (rc->remove() == 0) {         delete data;         delete rc;     } }   template<class t> msmartptr<t>::msmartptr(const msmartptr<t> &src): data(src.data), rc(src.rc) {     rc->add(); }   template <class t> t* msmartptr<t>::operator->() const {     return data; }  template<class t> t& msmartptr<t>::operator*() const {     return &data; }  template <class t> msmartptr<t>& msmartptr<t>::operator=( msmartptr<t> &src) {     if (this != &src) {         if (rc->remove() == 0) {             delete data;             delete rc;         }         data = src.data;         rc = src.rc;         rc->add();     }     return *this; }    #endif /* defined(__projectmanager__msharedptr__) */ 

let's application contains following classes:

class base { protected:     ... public:     virtual ~base() =0;     ... };   class derived1 : public base { protected:     ... public:     virtual ~derived1() {}     ... };  class derived2 : public base { protected:     ... public:     virtual ~derived2() {}     ... }; 

and need store data @ following way:

int int main(int argc, char const *argv[]) {     std::vector<msmartptr<base>> v;     msmartptr<derived1> d1 = foo();      v.push_back(d1);      return 0; } 

i need fix somehow cast operator, how? how base class in dynamic cast?

@guvante

your code did not work , modified follows don't know if work

template<class t> msmartptr<t> msmartptr<t>::operator ()(msmartptr<t>& src) {     msmartptr<t> retval(dynamic_cast<t*>(src.data));     retval.rc = src.rc;     retval.rc.add();     return retval; } 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -