Chronos
Chronos

Reputation: 91

Deep copy of a pointer to an array of pointers to objects

Edit: I originally posed this question out of context so I've reworked it. I've left as much as possible unchanged so most of your responses will still apply.

I'm having trouble understanding how to implement a constructor which accepts a pointer to an array of pointers.

I have the following class which contains a member, bodies, of type Body** (i.e. it is a pointer to an array of pointers to body objects).

class Galaxy
{
private:
   int n;          // Number of bodies in galaxy.
   Body** bodies;  // Ptr to arr of ptrs to Body objects.

public:
   Galaxy();
   Galaxy(int, Body**);

   // Some other member functions.
};

Here is the implementation of the constructors:

// Default constructor. Initializes bodies to null pointer.
Galaxy::Galaxy() : bodies(NULL) {}

// Alternate constructor. Here I try to perform a deep copy of bodiesIn.
Galaxy::Galaxy(int nIn, Body** bodiesIn)
{
   n = nIn;

   // Allocate memory for an array of n pointers to Body objects.
   bodies = new Body*[n];
   // Perform deep copy.
   for (int i=0; i<n; i++)
   {
      bodies[i] = new Body;
      *bodies[i] = *bodiesIn[i];
   }
}

Is this method sound, or is there a preferred way to construct such an object.

P.S. I realize it would be easier to code this with std::vector's, however the size of the array doesn't change, and minimizing memory usage is important.

Upvotes: 1

Views: 1974

Answers (1)

Deduplicator
Deduplicator

Reputation: 45654

There's lots wrong with your function:

  1. Creating an object and then immediately assigning to it is inefficient, use the copy ctor instead.
  2. If an exception is thrown by any new-expression but the first one or by one of the assignments, you are leaking objects.
  3. Better take a std::size_t for the size, it's designed for it.
  4. Better swap the arguments, that's more idiomatic.
  5. You don't return the copy at the moment
  6. Why not templatize it?

BTW: std::unique_ptr does not add any overhead, but provides plenty of comfort and safety.

Upvotes: 2

Related Questions