使用智能指针复制构造函数

Tin*_*Tin 6 c++ templates smart-pointers copy-constructor

我有一个班级,一个std::unique_ptr班级成员.我想知道,如何正确定义复制构造函数,因为我收到以下编译器错误消息:error C2248: std::unique_ptr<_Ty>::unique_ptr : cannot access private member declared in class 'std::unique_ptr<_Ty>.我的班级设计看起来像:

template <typename T>
class Foo{
    public:
        Foo(){};
        Foo( Bar<T> *, int );
        Foo( const Foo<T> & );
        ~Foo(){};

        void swap( Foo<T> & );
        Foo<T> operator = ( Foo<T> );

    private:
        std::unique_ptr<Bar> m_ptrBar;
        int m_Param1;

};

template < typename T >
Foo<T>::Foo( const Foo<T> & refFoo )
:m_ptrBar(refFoo.m_ptrBar), 
m_Param1(refFoo.m_Param1)
{
    // error here!
}

template < typename T >
void Foo<T>::swap( Foo<T> & refFoo ){
    using std::swap;
    swap(m_ptrBar, refFoo.m_ptrBar);
    swap(m_Param1, refFoo.m_Param1);
 }

 template < typename T >
 Foo<T> Foo<T>::operator = ( Foo<T> Elem ){
    Elem.swap(*this);
    return (*this);
 }
Run Code Online (Sandbox Code Playgroud)

Cub*_*bbi 5

假设目标是复制 - 构建独特拥有的Bar,

template < typename T >
Foo<T>::Foo( const Foo<T> & refFoo )
: m_ptrBar(refFoo.m_ptrBar ? new Bar(*refFoo.m_ptrBar) : nullptr),
  m_Param1(refFoo.m_Param1)
{
}
Run Code Online (Sandbox Code Playgroud)

  • @Tin:在这种情况下,你需要在基类中添加一个纯虚拟`clone()`函数,在每个派生类中重写以使用`new`创建一个副本.然后初始化变为`bar(foo.bar?foo.bar-> clone():nullptr)`. (2认同)