Reputation: 163
I have a simple question regarding pointer management in C++. When I am doing the following:
myTableWidget->setItem(j, i, new TableWidgetItem("something"));
if I understand well, I am creating a new pointer to a tablewidgetitem.
However, as I did not define any name, I cannot perform the delete
operation.
So, this will stay in memory all the time my program is running, right? Or is it something I do not understand?
Another thing is the following.
Suppose I have a class which takes 2 doubles
(for example ComplexNumber
class). The desctructor of my class is empty. However, if I call delete
on an element of my class ComplexNumber
, is it going to delete this element in my memory or just call the destructor which is empty ? If this element stays in memory all the running time, how can I program properly to delete it when I want to change the values of my table?
Example below:
complex.h
class Complex
{
public:
double r;
double i;
Complex(double, double);
~Complex();
};
complex.cpp
Complex::Complex(const double& real, const double& imaginary): r(real), i(imaginary)
{
}
Complex::~Complex():
{
}
main.cpp
int main(int argc, char *argv[])
{
Complex *a = new Complex a(2,3);
delete a;
}
In this case, is my memory free of a (a is destroyed in my memory and the double 2 and 3 are deleted) or it just does nothing as my destructor is empty?
Upvotes: 0
Views: 69
Reputation: 52461
If we are talking about QTableWidget::setItem
, then observe the documentation state "The table takes ownership of the item." This means the table object is responsible for destroying the item when it's no longer needed.
delete
expression does two things. First, it runs the destructor of the object pointed to by its operand. Then, it deallocates memory pointed to by its operand. In your example, the allocated memory is indeed freed.
Upvotes: 1