gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:27 25 4
gpt4 key购买 nike

我有一节课 std::unique_ptr作为类(class)成员。我想知道如何正确定义复制构造函数,因为我收到以下编译器错误消息:error C2248: std::unique_ptr<_Ty>::unique_ptr : cannot access private member declared in class 'std::unique_ptr<_Ty> .我的类(class)设计类似于:

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

最佳答案

假设目标是复制构造唯一拥有的 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)
{
}

关于c++ - 使用智能指针复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com