I have a class that looks like this :
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
vector<int*> V;
public:
MyClass();
MyClass(int n);
~MyClass();
};
MyClass::MyClass()
{
return;
}
MyClass::MyClass(int n)
{
int* T = new int[n];
for(int i=0; i<n; i++)
{
T[i]=i;
V.push_back(&(T[i]));
}
return;
}
MyClass::~MyClass()
{
for(int i =0; i<V.size(); i++)
delete V[i];
return;
}
int main()
{
MyClass C(5);
return 0;
}
Thanks in advance!
EDIT: Your intention is to have a vector of pointers, not arrays, so the problem is with your constructor:
int* T = new int[n];
for(int i=0; i<n; i++)
{
T[i]=i;
V.push_back(&(T[i]));
}
This doesn't create n
pointers, but a pointer to n
int
s. You should do:
for(int i=0; i<n; i++)
{
V.push_back(new int(i));
}
Before edit:
The problem isn't only in the destructor, but the constructor.
I'm assuming you want to push the array in the vector, in which case you need:
MyClass::MyClass(int n)
{
int* T = new int[n];
for(int i=0; i<n; i++)
{
T[i]=i;
}
V.push_back(T);
return;
}
You're also getting undefined behavior by calling
delete V[i];
instead of
delete[] V[i];
In your destructor, you're deleting pointers that were never allocated. You can only use delete
(or delete[]
) if there's a specific matching use of new
(or new[]
), and for n-1 of your int
pointers, there is no such call.
If you want your vector to hold pointers to individual unrelated int
s, then you need to use new
to allocate each one individually. If they're always going to be in an array like this, then keep a pointer to that array in a member, and delete just that one pointer in your destructor.
You are allocating a contiguous block of memory with
int *T = new int[n];
You cannot delete single elements of this block. You can only delete the entire block at once.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.