I’d like to know how C++ is dealing with memory of “objects” created by pointer inside class methods or functions.
For example method of class Example
void Example::methodExample()
{
ExampleObject *pointer = new ExampleObject("image.jpg");
}
Should i somehow delete this or it’s automatically removed?
Sorry if my question is stupid but i am beginner : P
You have two options.
If you use a raw pointer, as you are using in your example, you must manually
deleteobjects that were created withnew.If you don’t, you have created a memory leak.
Or you may use smart pointers, such as
boost::scoped_ptror C++11’sstd::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
ExampleObjectwill be correctly deleted even if an exception is thrown and the end of the function isn’t reached.