Skip to main content
Make title precise full question.
Link

C++ Vector How to avoid memory leaks when using a vector of Pointerspointers to Objectsdynamically allocated objects in C++?

renamed
Link
LihO
  • 42.3k
  • 11
  • 103
  • 169

C++ Vector of Pointers to Objects

Rewording.
Source Link
GManNickG
  • 506k
  • 55
  • 505
  • 551

Hey, what things do I need to be aware of, whileI'm using vectorsa vector of pointers to objects which are dynamically allocated. And yes, the class'sThese objects which I'm storing are derived from another type.

Can you tell those things which I should know to avoid memory leaksa base class, and are being dynamically allocated and stored.

Thanks

EDIT: My bad For example, I didn't specify what language I'm using. Btw, I'm using C++

I'm having a vectorhave something like this:

vector<Enemy*> Enemies;

and I'll be deriving from the Enemy class and then dynamically allocateallocating memory for the derived class and push them in the vector of base class pointers, like this:

enemies.push_back(new Monster());

What are things I need to be aware of to avoid memory leaks and other problems?

Hey, what things do I need to be aware of, while using vectors of pointers to objects which are dynamically allocated. And yes, the class's objects which I'm storing are derived from another type.

Can you tell those things which I should know to avoid memory leaks.

Thanks

EDIT: My bad, I didn't specify what language I'm using. Btw, I'm using C++

I'm having a vector like this:

vector<Enemy*> Enemies;

and I'll be deriving from the Enemy class and then dynamically allocate memory for the derived class and push them in the vector of base class pointers

enemies.push_back(new Monster());

I'm using a vector of pointers to objects. These objects are derived from a base class, and are being dynamically allocated and stored.

For example, I have something like:

vector<Enemy*> Enemies;

and I'll be deriving from the Enemy class and then dynamically allocating memory for the derived class, like this:

enemies.push_back(new Monster());

What are things I need to be aware of to avoid memory leaks and other problems?

added 261 characters in body
Source Link
akif
  • 12.4k
  • 25
  • 75
  • 86
Loading
added 83 characters in body; edited tags; edited title; edited body
Source Link
akif
  • 12.4k
  • 25
  • 75
  • 86
Loading
Source Link
akif
  • 12.4k
  • 25
  • 75
  • 86
Loading