ISLAM AHMED
ISLAM AHMED

Reputation: 1

How to deep copy structs having non trivial data members

I am facing an issue with smart pointers is when copying the structure having non trivial members like in this code:

struct ABC
{
int a;
std::vector<someType> b;
std::shared_ptr<sometype> c;
};

int main() 
{
 std::shared_ptr<ABC> ptr1 = std::make_shared<ABC>();
 /*
 *
 * allocating filling ptr's members
 *
 *
 *now somewhere else in the code we need to copy this content in a user context:*/

std::shared_ptr<ABC> anotherVar =  std::make_shared<ABC>(*ptr); /* I beleive this 
would not work here as it will only construct the parent struct ABC and do not copy 
the contents of its non-trivial members i.e "b" and "c". */
}

how to successfully deep copy the content of ptr to anotherVar?

Upvotes: 0

Views: 268

Answers (2)

divinas
divinas

Reputation: 1907

Your assumption is incorrect. The default copy constructor will invoke the copy constructor of each of your data members.

For the vector type, you'll get a new vector with the same contents. For the shared ptr, you'll get a a new shared ptr, pointing to the same resource.

If you want to create a shared ptr that is pointing to a copy of the original object's resource, then you'll need to implement your own versions of the big 5: Copy ctor, Copy Assign, Move Ctor, Move assign. You move assign and move ctor can most probably be made =default.

As pointed in the comments, if the pointed to type is polymorphic, you'll need a virtual clone method to invoke instead of a normal copy ctor.

Upvotes: 1

VLL
VLL

Reputation: 10165

You have to create copy constructors, for both ABC and someType (unless the default copy constructor of someType is sufficient):

struct ABC
{
    int a;
    std::vector<someType> b;
    std::shared_ptr<sometype> c;

    ABC() {}

    ABC(const ABS& other) : a(other.a),
        b(other.b), c(std::make_shared<ABC>(other.c))
    {}

    ABC& operator=(const ABS& other) {
        if (this != &other) {
            a = other.a;
            b = other.b;
            c = std::make_shared<ABC>(other.c);
        }
        return *this;
    }
};

Upvotes: 0

Related Questions