If there were code like
What happens to the new instance of some_object after exiting end_of_scope? Is it freed automatically? Or is this a potential memory leak?Code:beginning_of_scope
some_function(new some_object);
end_of_scope
If there were code like
What happens to the new instance of some_object after exiting end_of_scope? Is it freed automatically? Or is this a potential memory leak?Code:beginning_of_scope
some_function(new some_object);
end_of_scope
that leaks some_object.
It depends on what some_function() does.
So if I don't have a corresponding "delete" statement in some_function, this is a memory leak?
So I guess if you have a function that takes a pointer parameter, but has no idea where the referenced object was instantiated, then you should just do
rather than doing what I did above, just to save about two lines of code. Oh, well.Code:some_object* so = new some_object;
some_function(so);
delete so;
If you are going to do that, you should just write:
EDIT:Code:some_object so;
some_function(&so);
The problem is, what does some_function() do? Suppose that it will destroy the object pointed to via the pointer. Your second example would result in a double deletion and my example would result in an attempt to use delete on a pointer that points to a stack allocated object. Your first example would then be correct.
On the other hand, if some_function() does not destroy the object pointed to via the pointer, then your first example is wrong as it results in a memory leak.
If you need to use dynamic memory, you should look into using smart pointers like the ones in the Boost library -- they automatically delete themselves when nothing is referencing them anymore.
And just as importantly, they document intent. If the function parameter is a std::auto_ptr, the function will take possession of the object and you're to leave it alone after the function call. If it takes a shared_ptr, it will want to hold on to the object, but so can you. If it takes a reference, it won't hold on to the object at all, and - if you use these consistently - if it takes a pointer, it doesn't either, and the argument is optional or an array.