-
Simple question
PHP Code:
struct my_struct
{
//stuff
};
int main()
{
my_struct var;
//do stuff
var = my_struct(); //***
return 0;
}
Does the line with the asteriks beside it first call the my_struct destructor for the contents of var, and then the my_struct constructor?
-
>>Does the line with the asteriks beside it first call the my_struct destructor for the contents of var, and then the my_struct constructor?
First the constructor for var is called, then the constructor for the temporary is called, then the destructor for var is called and the temporary is assigned to var. Then when main exits that destructor is called.
-
So as long as the destructor of my_struct takes care of all the memory allocation that might have happened, there won't be any memory leaks doing it this way?
-
>>there won't be any memory leaks doing it this way?
As far as I can tell with the little example program you gave, but there are a lot of ways to cause a resource leak and watching your destructors won't stop all of them.
-
Re: Simple question
Quote:
Originally posted by pianorain
PHP Code:
struct my_struct
{
//stuff
};
int main()
{
my_struct var;
//do stuff
var = my_struct(); //***
return 0;
}
Does the line with the asteriks beside it first call the my_struct destructor for the contents of var, and then the my_struct constructor?
As far as I can see, you have 1) Default constructor 2) Default constructor for temp object and 3) Assignment operator
If memory is allocated in the construtor, and the assignment operator doesn't deallocate this memory, assigning your object in this manner will create a memory leak. Especially if you use the implicitly generated assignment operator provided by the compiler, as it just does a bitwise copy of members.
For example:
Code:
class myclass
{
public:
myclass() : m_a(new int[256]) {};
~myclass() { delete[] m_a; };
myclass &operator=(const myclass &rhs)
{
delete[] m_a;
m_a = rhs.m_a;
}
protected:
int *m_a;
}
That would be a proper definition free of memory leaks.
-
the contents of var are simply overwritten (bitwise copy) unless you override the = operator or provide a copy constructor. memory leaks are definately possible in this situation