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 new
and delete
in the correct order. There must be something better than that. Well, there is but it comes with its own can of worms.
Object Ownership
By Ilya Doroshenko
From the article:
Since we know the rules of
new
anddelete
, namelynew
allocates anddelete
destroys, 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 beLocalFree()
d, likeFormatMessage
orGetEnvironmentStrings
. POSIX, on the other hand, hasstrdup
as 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 callfree
ordelete
, 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 addauto_ptr
to the standard.The premise was simple:
- a simple explicit constructor, that took raw pointer from
new
- destroyed by either an explicit
release/reset
or a destructor on the end of the blockThis 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?
Add a Comment
Comments are closed.