Problems writing copy constructor for smart pointer

The code I'm working with has its own implementation of a smart pointer, which makes simple reference counting. Yes, we should not have our own implementation. Yes, we should use one of boost or some of them. The bear is with me.

I found that I wanted to write code like this:

...
CountedPointer<Base> base;
...
CountedPointer<Derived> derived;
...
base = derived;

However, the copy constructor for CountedPointer has a prototype similar to this:

CountedPointer(const CountedPointer<T> &other);

Thus, the above code will not compile since it cannot find a suitable constructor (or the assignment operator is the same story). I tried to rewrite the copy constructor with a prototype like this:

template<U>
CountedPointer(const CountedPointer<U> &other);

, , ( ), CountedPointer, .

Alexandrescu Loki, , , .

, , ?

Update: , . , , seg-faulted , , - . , , . , . .

+3
3

? :

template<typename T>
class CountedPointer {

    // ...

    template<U>
    CountedPointer(const CountedPointer<U> &other);

    template<typename U> friend class CountedPointer;
};
+4

"Alexandrescu Loki, , , "

, - , , . . . .

. , void * . ( Terred from U, ... T U?, .. ..), , :

class CountedPointerBase
{
    void* rawPtr;
};

template <class T>
class CountedPointer : public ConutedPointerBase
{
      T* myRawT = reinterpret_cast<T*>(rawPtr);

      template<class U>
      CountedPointer( CountedPointer<U> u)
      {
           // Copying a CountedPointer<T> -> CountedPointer<U>
           if (dynamic_cast<U*>(myRawT) != NULL)
           {
               // Safe to copy one rawPtr to another
           }
           // check for all other conversions
      }
}

, . , Loki/Boost, , .

, , , . . , , . , , - , ptr. , , .

+3

, CountedPointer (T * other); .

0

Source: https://habr.com/ru/post/1703428/


All Articles