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;
}
and:
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– ratchet freak2018年06月21日 23:40:08 +00:00Commented Jun 21, 2018 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– KIIV2018年06月22日 06:24:29 +00:00Commented Jun 22, 2018 at 6:24
1 Answer 1
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.
-
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– Mykolas2018年06月22日 14:48:35 +00:00Commented Jun 22, 2018 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– KIIV2018年06月22日 14:56:25 +00:00Commented Jun 22, 2018 at 14:56
-
I got it working by making template a friend of sared_ptr class. Thankyou for your helpMykolas– Mykolas2018年06月22日 14:57:23 +00:00Commented Jun 22, 2018 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– KIIV2018年06月22日 15:04:08 +00:00Commented Jun 22, 2018 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. @KIIVMykolas– Mykolas2018年06月22日 16:35:07 +00:00Commented Jun 22, 2018 at 16:35