You have two options.
If you use a raw pointer, as you are using in your example, you must manually delete
objects that were created with new
.
If you don't, you have created a memory leak.
void Example::methodExample()
{
ExampleObject *pointer = new ExampleObject("image.jpg");
// Stuff
delete pointer;
}
Or you may use smart pointers, such as boost::scoped_ptr
or C++11's std::unique_ptr
.
These objects will automatically delete their pointed-to contents when they are deleted.
Some (like me) will say that this approach is preferred, because your ExampleObject
will be correctly deleted even if an exception is thrown and the end of the function isn't reached.
void Example::methodExample()
{
boost::scoped_ptr<ExampleObject> pointer( new ExampleObject("image.jpg") );
// Stuff
}