Reputation: 592
This is my class definition and only copy constructor from a larger program. When my destructor executes, will it automatically release the 'coeff' memory? I believe that it does, however, my program throws a _CrtIsValidHeapPointer(pUserData) error after the program has been completed.
class Poly
{
private:
int order; //order of the polynomial
int size; //order + 1
int * coeff;//pointer to array of coeff on the heap
public:
Poly();
Poly(int Order);
Poly(int Order, int * Coeff);
~Poly(){cout << "Destructor\n";};
Poly(const Poly &rhs);
//accessors & mutators
void set();
void set(int * Coeff, int Order);
int getorder(){return order;};
int * get()const{return coeff;};
//Overloaded Operators
Poly operator+(const Poly &rhs);
Poly operator-(const Poly &rhs);
Poly operator*(const int scale);
Poly operator=(const Poly &rhs);
Poly operator*(const Poly &rhs);
const int& operator[](int I)const;
int& operator[](int I);
bool operator==(const Poly &rhs);
int operator( )(int X);
friend ostream & operator<<(ostream & Out, const Poly &rhs);
friend istream & operator >>(istream & In, Poly &rhs);
};
Poly::Poly(const Poly &rhs)
{
order = rhs.order;
size = rhs.size;
int *coeff = new int[size];
for(int i(0); i <= order; i++)
coeff[i] = rhs.coeff[i];
}
Thanks
Upvotes: 0
Views: 88
Reputation: 56479
Destructor will do as your code, nothing more. Your destructor just prints a message. Try below code:
~Poly() {
delete [] coeff; // if you allocated memory by new in constructor!
}
As a hint, try not to use bare pointers. There are always std::vector
, std::unique_ptr
,...
Upvotes: 0
Reputation: 4012
The destructor takes care of any memory that the constructor allocated automatically, it won't do anything more. So if you allocated memory by yourself (like when you used new
), the destructor will leave it. If it would behave differently, it could destroy data you're using in a different place of the program. That's why it doesn't do delete
on variables you created with new
or new[]
.
Check your IDE documentation hovewer, because it can have a cleanup mechanism that clears all data after the program shuts, and it can embed that mechanism automatically in your output code.
Upvotes: 1
Reputation: 31647
The destructor will only cout << "Destructor\n"
. It will not release any memory.
Upvotes: 1