I am using custom shared_ptr class for some program on Arduino, and I need to do something like this:

shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

In my shared_ptr class I have three constructors:

shared_ptr() : pData(0), reference(0){...}
shared_ptr(T* pValue) : pData(pValue), reference(0){...}
shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

and some other stuff... For casting I tried to write the following:

    template< typename T2 >
operator T2 * () const
   return (T2 *)pData;


    template< typename T2 >
operator shared_ptr<T2> () const
    shared_ptr<T2> temp((T2 *)pData);
    return temp;

but can't get it to work.

  • why do you need a shared ptr in the first place? there's not a lot of memory to warrant dynamic allocation for objects in the first place... – ratchet freak Jun 21 '18 at 23:40
  • It's better not to use C-style casting in C++. It's working for POD types, but it's basically saying this pointer to elephant is now pointer to train. You should learn about static_cast and dynamic_cast (but I'd skip reinterpret_cast as it's roughly equivalent to the C-style casting) – KIIV Jun 22 '18 at 6:24

For doing:

shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr(b_ptr);

you have to use another constructor. If you take a look on this Example of shared_ptr implementation, you can see:

template<class U> shared_ptr(const shared_ptr<U>& s) ...

That's exactly the constructor, that takes shared_ptr of different type .

And similarly for assigment operator.

| improve this answer | |
  • Thankyou for you answer. But how will I initialize private data like: pData(s.pData), reference(s.reference)? I can't access them directly, since now they are other class members. – Mykolas Jun 22 '18 at 14:48
  • I don't know much about your shared_ptr class. Anyways, you can assign pointer to the child into pointer to the parent directly (by implicit conversion). – KIIV Jun 22 '18 at 14:56
  • I got it working by making template a friend of sared_ptr class. Thankyou for your help – Mykolas Jun 22 '18 at 14:57
  • @Mykolas Btw, if the reference is class member, it'll never work. You have to use something common for all copies. – KIIV Jun 22 '18 at 15:04
  • Yes, I know. The reference is a separate class. Each shared_ptr object stores a pointer to this related reference object. Thankyou for the comment. @KIIV – Mykolas Jun 22 '18 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.