Search code examples
c++boostdeep-copy

deep copy for C++ boost::shared_ptr


I am trying to do deep copy for C++ boost::shared_ptr.

struct A{
   boost::shared_ptr<const Data> dataPtr;

   A(const A& aSource) {
      dataPtr.reset(new const Data);
      *dataPtr  = *(aSource.dataPtr);
};

But, i got error: error: uninitialized const in 'new' of 'const struct A.

If I do not want to drop const, how to handle that ?

Any help will be appreciated.

Thanks !


Solution

  • That is because you are trying to modify (in particular, to assign) a value through a const reference to it (because this is what dereferencing a shared_ptr to const gives you). Supposing Data has a copy constructor, you should rewrite your program this way:

    struct A
    {
        boost::shared_ptr<const Data> dataPtr;
    
        A(A const& aSource)
        {
            dataPtr.reset(new Data(*(aSource.dataPtr)));
        }
    };