Possible Duplicate:
Does using references instead of pointers, resolve memory leaks in C++?
When I ask this question
Does using references instead of pointers, resolve memory leaks in C++?
A new question appears and I ask it in this post.
Does this code leak memory?
class my_class
{
...
};
my_class& func()
{
my_class* c = new my_class;
return *c;
}
int main()
{
my_class& var1 = func();
// I think there is no memory leak.
return 0;
}
Yes, it does leak memory. Everything that was created by new
has to be destroyed by delete
. There's new
in your code, but no delete
. That immediately means that the new
ed memory is leaked.
It does create a memory leak. Look at this example:
int main()
{
my_class var1;
my_class& var2 = var1;
...
}
Here the destructor for var1 will only be called once, if your assumtions were true, it would be called twice.
Yes, you have to free every instance of an object u allocated using the 'new' operator or using the 'malloc' function.
Make sure you clear the memory by using 'delete' when you are done.