This article goes over the spicy topic of object ownership. We covered the lifetime quirks, and we found out that manual memory management can be a nightmare, we
delete in the correct order. There must be something better than that. Well, there is but it comes with its own can of worms.
By Ilya Doroshenko
From the article:
Since we know the rules of
deletedestroys, we never really cared about who is responsible for the object. This caused a lot of confusion in the past. For instance, some API codes from Win32 return strings that should be
GetEnvironmentStrings. POSIX, on the other hand, has
strdupas a common example of you should free it yourself. This model is confusing because you may have a lot of return statements, before which you should always call
delete, depending on the operation. However, we have RAII since the very beginning of C++, which adds constructors and destructors. So, in 1998 resourceful people decided to add
auto_ptrto the standard.
The premise was simple:
- a simple explicit constructor, that took raw pointer from
- destroyed by either an explicit
release/resetor a destructor on the end of the block
This was the first attempt at a structured cleanup. As time passed, the initial point began to crumble. More issues arose and the question came up: Who owns the data?