c++ - std::shared_ptr 的实例化类型丢失 const

标签 c++ c++11

给定以下程序:

#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:

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

显然,我不希望能够转换 一个SharedPtr<D const>SharedPtr<D> (或者 一个std::shared_ptr<D const>std::shared_ptr<D> , 这是 微软提示什么)。但是在哪里 SharedPtr<D>最初来自哪里?我什么也看不见 上面代码中的东西应该创建任何智能指针 任何类型到非常量。

最佳答案

这个构造函数:

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 ) {}

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

关于c++ - std::shared_ptr 的实例化类型丢失 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717560/

相关文章:

c++ - 如何使用 `static linking` 和 `Dynamic linking` 以及 gcc 和 Visual Studio 构建 C/C++ 程序?

c++ - Arduino char* 数组[] : "vanishing" characters

c++ - 调用重载运算符失败时用户定义的枚举类隐式转换

c++ - 开关在 C++ 中不起作用

c++ - 重新定义 QTreeWidgetItem::operator<

c++ - 为什么实例化数组比 glDrawElement 慢?

c++ - 多个对象无法渲染?

c++ - 为什么在 C++ 中调用原始类型的构造函数是合法的?

c++ - 将 std::function 移动到另一个 std::function 不会在捕获的变量上调用移动构造函数

c++ - 如何验证运行时失败是否是由于生成的线程过多造成的?