1

Let's assume I have a class which contains a dynamically allocated member, as shown below:

class example
{
  private:
          otherClass * pointer;
  public:
          example(int foo){ pointer = new otherClass(foo); }
          ~example(){delete pointer;}
};
//defining template parameter
example template(1);

Now lets assume that I want to dynamically push_back that template object into a vector, as shown below:

std::vector<example> myVector;
for(int i=0; i<5; i++)
   myVector.push_back(template);
myVector.erase(myVector.begin());

My question is: How do I prepare the class to handle dynamically allocated pointers? I know I need to overload the copy constructor, but do I also need to overload the copy assignment? what about move constryctor or move assignment? Are there any other precautions that I forgot about?

Raven
  • 648
  • 1
  • 7
  • 18

2 Answers2

0

I am not sure I understood well your problem, so I will start first by telling what I undrestood.

  • Your vector after the for loop contains 5 objects. Each of those objects points to the same oject of otherClass.
  • Once you will erase one object, the destructor will be automatically called and the object of otherClass will be deleted.

The problem is that the 4 remaining objects in vector point now to some memory that was already deleted.

the solution to your problem in my opinion is to change the definition of your class and use Reference Counting Smart Pointers.

class example
{
  private:
      std::shared_ptr<otherClass> pointer;
  public:
      example(int foo) : pointer(new otherClass(foo)){ }
      ~example(){}
};

This way, only deleting the 5th object from your vector will delete the object of otherClass.

Issam T.
  • 1,677
  • 1
  • 14
  • 32
0

How do I prepare the class to handle dynamically allocated pointers? I know I need to overload the copy constructor, but do I also need to overload the copy assignment? what about move constryctor or move assignment?

There are three choices how to implement copying of the dynamically allocated members:

  1. Disable copying by making the copy constructor and assignment operator non-private or deleted.
  2. Shallow copy of the pointer members by using pointers with shared ownership semantics, such as std::shared_ptr. Use the compiler generated copy constructor and assignment.
  3. Deep copy. By storing members by value and using the compiler generated copy constructor and assignment, or, for pointer members, allocating new copies in the user defined copy constructor and assignment operator along with the move overloads.
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271