3

给定以下程序:

#include <memory>

template <typename T>
class SharedPtr : public std::shared_ptr<T>
{
    typedef std::shared_ptr<T> Impl;
    template<typename U> friend class SharedPtr;
    SharedPtr( Impl const& other ) : Impl( other ) {}
public:
    SharedPtr( T* newed_ptr ) : Impl( newed_ptr ) {}
    SharedPtr( SharedPtr const& other ) throw() : Impl( other ) {}
    template <typename U> SharedPtr( SharedPtr<U> const& other ) throw() : Impl( other ) {}

    template <typename U> SharedPtr<U> DynamicCast() const throw()
    {
        return SharedPtr<U>( std::dynamic_pointer_cast<U>( *this ) );
    }
};

template<typename T> class Handle : public SharedPtr<T const>
{
    typedef SharedPtr<T const> Base;
    template <typename U> friend class Handle;
public:
    explicit Handle( T const* pObject = 0 ) : Base( pObject ) {}
    Handle( SharedPtr<T> const& src ) : Base( src ) {}
    template <typename Derived>
    Handle( Handle<Derived> const& other ) : Base( other ) {}
    template <typename Derived>
    Handle<Derived> DynamicCast() const throw() {
        SharedPtr<Derived const> tmp = this->Base::template DynamicCast<Derived const>();
        return Handle<Derived>( tmp );
    }
};

class B { public: virtual ~B() {} };
class D : public B{};

void
testit()
{
    Handle<D> p( new D );
    Handle<B> p1( p );
    Handle<D> p2( p1.DynamicCast<D>() );
}

我收到以下错误(来自 g++ 4.7.2):

noX.cc: In instantiation of ‘SharedPtr<T>::SharedPtr(const SharedPtr<U>&) [with U = const D; T = D]’:
noX.cc|33 col 37| required from ‘Handle<Derived> Handle<T>::DynamicCast() const [with Derived = D; T = B]’
noX.cc|45 col 37| required from here
noX.cc|13 col 88| error: no matching function for call to ‘std::shared_ptr<D>::shared_ptr(const SharedPtr<const D>&)’
noX.cc|13 col 88| note: candidates are:

和一长串候选人。Microsoft (MSVC 11) 给出了类似的消息,所以我假设错误在我的代码中,而不是编译器错误。

显然,我不希望能够将 a 转换SharedPtr<D const>为 a SharedPtr<D>(或 astd::shared_ptr<D const>到 a std::shared_ptr<D>,这是微软所抱怨的)。但是 SharedPtr<D>首先从哪里来?我在上面的代码中看不到任何应该创建任何类型的非 const 智能指针的东西。

4

3 回答 3

4

这个构造函数:

Handle( SharedPtr<T> const& src ) : Base( src ) {}

依赖于从SharedPtr<T>SharedPtr<T const>(即Base)的隐式转换。但在这儿:

return Handle<Derived>( tmp );

您需要SharedPtr<T const>->Handle<T>转换,尽管唯一可能的候选者是构造函数采用SharedPtr<T>. 一种解决方案是将其更改为:

Handle(Base const& src ) : Base( src ) {}

如果需要,将隐式转换“移动”给调用者。

于 2013-05-23T15:23:53.640 回答
3
template<typename T> class Handle : public SharedPtr<T const>
{
    Handle( SharedPtr<T> const& src ) : Base( src ) {}

    Handle<Derived> DynamicCast() const throw() {
        SharedPtr<Derived const> tmp = this->Base::template DynamicCast<Derived const>();
        return Handle<Derived>( tmp );
    }

您的返回 a Handlewhere T 是Derived没有 const 的类型。T inSharedPtr<T>是类型Derived const

于 2013-05-23T15:19:45.403 回答
3

乍一看,似乎SharedPtr<Derived>正在为Handle( SharedPtr<T> const& src )调用隐式创建一个对象return Handle<Derived>( tmp );

于 2013-05-23T15:20:29.960 回答