Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor with smart pointer

I have a class with one std::unique_ptr as class member. I was wondering, how to correctly define the copy constructor, since I'm getting the following compiler error message: error C2248: std::unique_ptr<_Ty>::unique_ptr : cannot access private member declared in class 'std::unique_ptr<_Ty>. My class design looks something like:

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);
 }
like image 732
Tin Avatar asked Nov 29 '11 18:11

Tin


People also ask

Can we use pointer in copy constructor?

Technically, you could write a constructor that takes a pointer (although it's technically not a copy constructor in that case, based on the wording of the spec). However, this prevents you from using non-addressable results.

How do you copy a smart pointer?

Basically, smart pointers are class templates that encapsulate a raw pointer and free memory in the destructor. This makes RAII possible, a fundamental idiom for resource management in modern C++. There is only one smart pointer referring to an object at the same time and the smart pointer cannot be copied.

What happens when copy constructor of shared pointer called?

The copy constructor for std::shared_ptr creates a second pointer which shared ownership with the first pointer. The pointee will be destroyed when all std::shared_ptr that point to it are destroyed.

Does Make_shared create a copy?

std::make_shared<T>(*this) would make a new copy of the object which is owned by the new shared_ptr .


1 Answers

Assuming the goal is to copy-construct the uniquely-owned 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)
{
}
like image 99
Cubbi Avatar answered Sep 27 '22 16:09

Cubbi