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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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.
Last edited by laserlight; 02-08-2009 at 08:52 PM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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.
"I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008
"the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010
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.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law