I got this code going on, and my only question is this:
when the compiler gets to the delete pa2 part of the program, what happens to the allocated vector which I made using the constructor? Does the deconstructor get called and the array will be deleted from memry too, or it's just the pointer that's going to lose the link to the address of that newly allocated X and the object X remains in memory? Thank you for your time!
#include <iostream>
using namespace std;
class X {
public:
float* vector;
X() {
this->vector = new float[10];
for (int i = 0; i < 10; i ) {
vector[i] = 1;
}
}
X(float* v) {
this->vector = new float[3];
for (int i = 0; i < 3; i ) {
this->vector[i] = v[i];
}
delete[]v;
}
~X() {
delete[]this->vector;
}
};
int main() {
X a1;
X a2(new float[3]{ 100, 100.5, 200 });
X* pa2 = new X(new float[3]{ 100, 100.5, 200 });
cout << pa2 << endl;
cout << pa2->vector[0];
delete pa2;
}
I tried deleting the pa2, as seen in the code, but I am not sure whether the dynamically allocated vector (the one passed for the constructor of X on X* pa2) will also be deleted from Heap Memory or not.
CodePudding user response:
The array created by new float[3]{ 100, 100.5, 200 }
will already be deleted in the X(float *v)
constructor.
The array pa2->vector
is also delete[]
d, but that happens in the destructor ~X
when you call delete pa2;
. This array, however, was created in the constructor, so it's a different one from the array that was passed to the constructor.
In short: there are no memory leaks here.
That said, the whole thing could be a lot simpler if you would use std::vector
instead of raw arrays:
#include <iostream>
#include <vector>
class X {
public:
std::vector<float> vector;
X() {
for (int i = 0; i < 10; i ) {
vector.push_back(1);
}
}
X(std::vector<float> vector) {
this->vector = vector;
}
};
int main() {
X a1;
X a2({ 100, 100.5, 200 });
X* pa2 = new X({ 100, 100.5, 200 });
std::cout << pa2 << std::endl;
std::cout << pa2->vector[0] << std::endl;
delete pa2;
}
CodePudding user response:
what happens to the allocated vector
It gets delete[]
ed because the destructor, ~X()
, will be called when you do delete pa2;
.
There's no difference between how an X
created on the stack
X a2(new float[3]{ 100, 100.5, 200 });
or on the heap
X* pa2 = new X(new float[3]{ 100, 100.5, 200 });
delete pa2;
cleans up its resources. You use the same constructor and destructor in both these cases.
If you run it in a debugger or add std::cout << "~X()\n";
to the destructor, you can see that.
~X() {
std::cout << "~X()\n"; // simple alternative to running it in a debugger
delete[] this->vector;
}
I am not sure whether the dynamically allocated vector (the one passed for the constructor of X on X* pa2) will also be deleted from Heap Memory
The constructor does exactly the same thing in both cases. It allocates a new vector, copies the data from the vector you've supplied as an argument and then delete[]
s the vector supplied as an argument.