{"id":780,"date":"2023-07-28T09:28:15","date_gmt":"2023-07-28T09:28:15","guid":{"rendered":"https:\/\/tbekk.com\/devstream\/?p=780"},"modified":"2023-07-28T09:37:15","modified_gmt":"2023-07-28T09:37:15","slug":"object-ownership","status":"publish","type":"post","link":"https:\/\/tbekk.com\/devstream\/2023\/07\/28\/object-ownership\/","title":{"rendered":"Object Ownership"},"content":{"rendered":"\n<hr class=\"wp-block-separator has-text-color has-light-gray-color has-alpha-channel-opacity has-light-gray-background-color has-background is-style-wide\"\/>\n\n\n\n<ul class=\"wp-block-list\">\n<li><em><strong>Link:<\/strong> <\/em><a href=\"https:\/\/www.kdab.com\/object-ownership\/\">kdab.com\/object-ownership<\/a><\/li>\n\n\n\n<li><strong><em>Author: <\/em><\/strong><a href=\"https:\/\/www.kdab.com\/author\/ilya-doroshenko\/\"><em>Ilya Doroshenko<\/em><\/a><\/li>\n\n\n\n<li><em><strong>Publication date: <\/strong>July 5, 2023<\/em><\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-light-gray-color has-alpha-channel-opacity has-light-gray-background-color has-background is-style-wide\"\/>\n\n\n\n<p><a href=\"https:\/\/www.kdab.com\/object-lifetime\/\">Last time<\/a>&nbsp;we touched upon object lifetime and today we wrap up the basics with a bit of a spicy topic of object ownership. We covered the lifetime quirks, and we found out that manual memory management can be a nightmare, even if we&nbsp;<code>new<\/code>&nbsp;and&nbsp;<code>delete<\/code>&nbsp;in the correct order. There must be something better than that. Well, there is but it comes with its own can of worms.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Structured cleanup<\/h2>\n\n\n\n<p>Since we know the rules of&nbsp;<code>new<\/code>&nbsp;and&nbsp;<code>delete<\/code>, namely&nbsp;<code>new<\/code>&nbsp;allocates and&nbsp;<code>delete<\/code>&nbsp;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 be&nbsp;<code>LocalFree()<\/code>d, like&nbsp;<code>FormatMessage<\/code>&nbsp;or&nbsp;<code>GetEnvironmentStrings<\/code>. POSIX, on the other hand, has&nbsp;<code>strdup<\/code>&nbsp;as a common example of&nbsp;<em>you should free it yourself.&nbsp;<\/em>This model is confusing because you may have a lot of return statements, before which you should always call&nbsp;<code>free<\/code>&nbsp;or&nbsp;<code>delete<\/code>, 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&nbsp;<a href=\"https:\/\/en.cppreference.com\/w\/cpp\/memory\/auto_ptr\"><code>auto_ptr<\/code><\/a>&nbsp;to the standard.<\/p>\n\n\n\n<p>The premise was simple:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>a simple explicit constructor, that took raw pointer from&nbsp;<code>new<\/code><\/li>\n\n\n\n<li>destroyed by either an explicit&nbsp;<code>release\/reset<\/code>&nbsp;or a destructor on the end of the block<\/li>\n<\/ul>\n\n\n\n<p>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:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Who owns the data?<\/h2>\n\n\n\n<p>Of course, the data is owned by the pointer class. But what if the data is needed elsewhere? In C++98 the only options were reference and raw pointer. If you copied the&nbsp;<code>auto_ptr<\/code>&nbsp;to another place it moved itself to that location, essentially transferring the ownership. That made it impossible to place them into standard containers since the copy of the object did not adhere to copy semantics at all, and the objects were not equal.<\/p>\n\n\n\n<p>Simple example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">auto_ptr&lt;CPClass&gt; a(new CPClass);\nauto_ptr&lt;CPClass&gt; b(a); \/\/copy the a\n\nprintf(\"%p\", a.get()); \/\/ prints 0\nprintf(\"%p\", b.get()); \/\/ prints valid pointer<\/pre>\n\n\n\n<p>Another set of problems included inability to express custom deletions for allocated arrays,&nbsp;<code>malloc<\/code>&nbsp;allocation, or any specific destructor at all. Quite problematic one might say. C++11 invented move semantics, and along with them new types of pointers;&nbsp;<code>unique_ptr<\/code>&nbsp;was one of them. It disabled copying altogether, which forcd containers like vector to move the contents instead. Furthermore, the argument template also got a custom deleter possibility for custom pointers, array overload and fancy&nbsp;<code>make_unique&lt;&gt;.<\/code>&nbsp;This is a replacement for explicit&nbsp;<code>new<\/code>&nbsp;call, though, it lacks a custom deleter. For that usage you still have to use an explicit constructor. In the same standard&nbsp;<code>auto_ptr<\/code>&nbsp;was deprecated and it was removed completely in C++17.<\/p>\n\n\n\n<p>Now for some express wordings: Object 1 owns another Object 2, if 2\u2019s lifetime does not exceed 1\u2019s and object 1 is responsible for destroying object 2. For fellow mathematicians, it is a weak ordering of lifetime.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/www.kdab.com\/object-lifetime\/\"><img decoding=\"async\" src=\"https:\/\/www.kdab.com\/wp-content\/uploads\/stories\/a.drawio.svg\" alt=\"\" class=\"wp-image-32171\"\/><\/a><\/figure>\n\n\n\n<p>The object may be destroyed earlier than its holder, but not the other way around.&nbsp;<code>auto_ptr<\/code>&nbsp;uniquely owns memory, hence, you can say, that it is a unique pointer. Well, kind of. But the implicit ownership transfer did not allow it to be stable enough. The&nbsp;<code>unique_ptr<\/code>&nbsp;came out and said: \u201cI own the memory! And if you want it, then you will have to take it.\u201d<\/p>\n\n\n\n<p>Although two more pointers came along with&nbsp;<code>unique_ptr<\/code>, this is where we should dive a bit deeper.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Shared ownership<\/h2>\n\n\n\n<p>Let\u2019s imagine the case, where there are several objects that communicate with one particular one. The easiest example from the real world is the communication with a printer from several devices.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"alignleft\"><a href=\"https:\/\/www.kdab.com\/wp-content\/uploads\/stories\/aaa.drawio-2.svg\"><img decoding=\"async\" src=\"https:\/\/www.kdab.com\/wp-content\/uploads\/stories\/aaa.drawio-2.svg\" alt=\"\" class=\"wp-image-32170\"\/><\/a><\/figure><\/div>\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<p>If we project the same logic to the code, we could expect an object, which represents the printer inside the objects, which represent devices. Pretty simple, isn\u2019t it? Now we impose a restriction: If the printer is out of scope, it shuts down.<\/p>\n\n\n\n<p>Suddenly, the task becomes complex since we can\u2019t say explicitly who owns the printer, and we need to keep it alive, while every device keeps working with it.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Component Object Model<\/h4>\n\n\n\n<p>The solution would require sharing the ownership between the consumers. How can we solve that? Microsoft pondered about this question and invented COM. Of course, I oversimplify because COM actually solves a lot more than simply sharing, but also hiding the implementation details, uniform representations, ABI control, cross-process communications, etc. But the one thing it does with it is the so-called reference counting. It counts how many objects own the COM interface and does the cleanup when all the consumers are out and refcount is 0.<\/p>\n\n\n\n<p>Here the object itself is responsible for deleting itself and not the consumer, and the same function cleans the underlying memory, which is also responsible for releasing a reference called&nbsp;<code>Release<\/code>. Such a model is a bit confusing at first, but bearg in mind that it was invented even before C++98, in 1993 to be exact, everything comes into place. Does your complex object have some very hard destruction process aside from just&nbsp;<code>delete<\/code>? Maybe it is part of a memory pool and the memory should just go back to it? Fear not,&nbsp;<code>interface-&gt;Release()<\/code>&nbsp;got it for you. (The class should still implement the&nbsp;<code>Release<\/code>&nbsp;function; so, no magic here). The model is quite robust and is still in use by Microsoft to this day. Later iterations of Windows API included RAII wrappers, such as ATL&nbsp;<code>CComPtr<\/code>&nbsp;and&nbsp;<code>CComQIPtr<\/code>, WRL&nbsp;<code>Microsoft::WRL::ComPtr<\/code>&nbsp;and finally WinRT with&nbsp;<code>winrt::com_ptr<\/code>. All for their needs but with one purpose.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Explicit sharing<\/h4>\n\n\n\n<p>Well, of course, COM looked like a miracle back in the day. While it was a bit clumsy with implementation, it was doing its job. But what if we are not on Windows? You can still emulate COM and it will in fact work just as well. But implementing it is a nightmare for a regular programmer. C++11 added&nbsp;<code>shared_ptr<\/code>, which did the same job of sharing the data using atomic reference counting. It did not put the responsibility of destruction to the object, but called destruction himself. Also coming packed with custom deleter and array overloads (which were mostly missing for COM), it came with a particular function, which felt the same as&nbsp;<code>make_unique<\/code>.&nbsp;<code>make_shared<\/code>&nbsp;provided a way to construct a simple&nbsp;<code>shared_pointer<\/code>, but it is storing the reference counter with the object, when constructor allocates two blocks of memory; one for ref counter and one for the object itself.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Curse of sharing<\/h2>\n\n\n\n<p>So far, we have discussed only strong points, but what came with&nbsp;<code>shared_ptr<\/code>&nbsp;was a big problem. COM model enforced strict rules for marshalling and modification of the internal state, as well as concurrent access. Also COM always exported only interfaces, so the state stability was on the developer of the implementation. But shared pointer didn\u2019t do anything in that regard, leaving room for a lot of bugs and exploits, that came along.<\/p>\n\n\n\n<p>What is the problem? As we already know from&nbsp;<a href=\"https:\/\/www.kdab.com\/value-semantics\/\">Value Semantics<\/a>, sharing a reference is bad, and often leads to entanglement and fragility of the code. There is one particular case, that I have seen in practice:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">struct B;\nstruct A{\n...\nstd::shared_ptr&lt;B&gt; b;\n}\nstruct B{\n...\nstd::shared_ptr&lt;A&gt; a;\n}<\/pre>\n\n\n\n<p>I can construct either of those, but let\u2019s choose A:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">int main(){\nstd::shared_ptr&lt;A&gt; a = std::make_shared&lt;A&gt;();\nstd::shared_ptr&lt;B&gt; a = std::make_shared&lt;B&gt;();\na-&gt;b = b;\nb-&gt;a = a;\n}<\/pre>\n\n\n\n<p>Now, tell me, who owns who? What will happen after the&nbsp;<code>main()<\/code>?<\/p>\n\n\n\n<p>The memory obviously will leak since we have created a quantum entanglement. This is obvious but the real example may not be, what if A and B are connected through several other classes? Debugging such a leak is borderline impossible! Of course, there is&nbsp;<code>weak_ptr<\/code>&nbsp;which solves the deal, but it is still hard to twist your mind around that. To fix the problem we need to:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">struct B;\nstruct A{\n...\nstd::shared_ptr&lt;B&gt; b;\n}\nstruct B{\n...\nstd::weak_ptr&lt;A&gt; a;\n}\nint main(){\nstd::shared_ptr&lt;A&gt; a = std::make_shared&lt;A&gt;();\nstd::shared_ptr&lt;B&gt; a = std::make_shared&lt;B&gt;();\na-&gt;b = b;\nb-&gt;a = a;\n}<\/pre>\n\n\n\n<p>Now everything is going to be deallocated after the main ends.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p><code>unique_ptr<\/code>&nbsp;is a solid tool to ensure an object is only used in one place at a time. Great for value semantics, it does not break anything, robust.&nbsp;<code>shared_ptr<\/code>, on the other hand, is bad\u2026 Just kidding! Although the menace is lurking around, if you are sure, the state of underlying object is immutable, exempli gratia: a pool of shared textures for a game, it is fine. It is a bad design to share state, and it must be done sparingly and only in cases, where it is absolutely necessary!&nbsp;<code>weak_ptr<\/code>&nbsp;does not share state, and is a great helper to brake strong bonds, although I should mention costs of checking if the allocated object is alive. This may kill the performance \u2013 hence, still no magic solution.<\/p>\n\n\n\n<p>Now we have made our way as close to the coroutine world as possible, we are ready to use the knowledge to our advantage and build predictable code. And remember unique \u2013 good, shared + immutable also good.<\/p>\n\n\n\n<p>Enjoy advanced object lifetime!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Last time&nbsp;we touched upon object lifetime and today we wrap up the basics with a bit of a spicy topic of object ownership. We covered the lifetime quirks, and we&#8230; <a class=\"read-more-link\" href=\"https:\/\/tbekk.com\/devstream\/2023\/07\/28\/object-ownership\/\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[51,220,87],"tags":[77,227,229],"class_list":["post-780","post","type-post","status-publish","format-standard","hentry","category-article","category-cpp","category-coding","tag-c-3","tag-c23","tag-object-ownership"],"_links":{"self":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/780","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/comments?post=780"}],"version-history":[{"count":2,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/780\/revisions"}],"predecessor-version":[{"id":784,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/780\/revisions\/784"}],"wp:attachment":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/media?parent=780"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/categories?post=780"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/tags?post=780"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}