chuchi
August 9th, 2017, 11:38 AM
Hi everyone!
I have to deal with a memory leak in a code that is not mine, and I want to ask for advice on what is an elegant way to free the memory leak. The code looks like this:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
int a;
A(int a_) : a(a_)
{}
};
class B
{
public:
B(A * a) : a_(a)
{
}
private:
A *a_;
};
class Example
{
public:
void createElements(int count)
{
vectorB.clear();
for (int i = 0; i < count; i++)
{
A * a = new A(i);
B b(a);
vectorB.push_back(b);
}
}
private:
std::vector <B> vectorB;
};
int main()
{
Example example;
example.createElements(3);
}
The memory leak comes from the line :
A * a = new A(i);
I thought that maybe I could maintain a vector<A*> and add the objects to this vector. Then, when deleting Example (or when calling createElements again) I would iterate through that vector, free its elements and clear the vector.
What do you think about this approach?
Thanks a lot!
I have to deal with a memory leak in a code that is not mine, and I want to ask for advice on what is an elegant way to free the memory leak. The code looks like this:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
int a;
A(int a_) : a(a_)
{}
};
class B
{
public:
B(A * a) : a_(a)
{
}
private:
A *a_;
};
class Example
{
public:
void createElements(int count)
{
vectorB.clear();
for (int i = 0; i < count; i++)
{
A * a = new A(i);
B b(a);
vectorB.push_back(b);
}
}
private:
std::vector <B> vectorB;
};
int main()
{
Example example;
example.createElements(3);
}
The memory leak comes from the line :
A * a = new A(i);
I thought that maybe I could maintain a vector<A*> and add the objects to this vector. Then, when deleting Example (or when calling createElements again) I would iterate through that vector, free its elements and clear the vector.
What do you think about this approach?
Thanks a lot!