Single Ownership in C++ (intro to auto_ptr) 22

Posted by tottinger Fri, 30 Mar 2007 15:48:00 GMT

I find a lot of C++ programmers experience memory management differently than I do. I used to have the same kinds of problems that they have, but I learned an important rule: every heap object has exactly one owner, and n borrowers.

The way that I realize this is using reference types. Of course, all good C++ programmers write their functions to use the canonical “const T&” parameters whenever possible. Using a reference means that we have an actual object and not a null reference (side effect: no null checks) and we have simple dot notation (side effect: less typing), but I also use this to mean that we are borrowing the object, not owning it. Likewise, if we have to drop the ‘const’, we are still borrowing.

What about passing by pointer? I only do that if I absolutely must accept 0 (null) as a possible value. I always hate to do that. I would rather have an object outright than a pointer that I dereference. If the function is being called by a framework, I don’t get a choice. I might do something like this:
     void functionName(const Snorkle* snorkleWithNull) {
             if (0 == snorkleWithNull) { 
                  throw SomeIdiotPassedMeANull();
            const Snorkle& snorkle = snorkleWithNull;

           // ... work with snorkle, ignore snorkleWithNull ... 

     }
However sick that seems (and it does) it reverts back to the const reference case quickly and I’m left with a reference to a real object. It keeps me from forgetting to dereference when I’m in a hurry, and keeps me from casting. I have to work extra-hard to do bad things, and that’s a good thing. On the other hand, in modern TDD style, with refactoring, it can double the length of a function (hence feeling sick).

Either way, if you are a borrower, you have no right to delete the object. You can reference it for the duration of your function, or (if the intent is that you will have a short-lived object) for the duration of the object lifetime, but no ownership is given by pointer or reference. Remember that we still have a risk of the pointer being dangled, so holding a reference/pointer for longer than a method call should be considered fairly dangerous and must be done rather intentionally.

But what about transfer of ownership? That’s what the auto_ptr in <memory> is for. Yes, it’s a template. If I can’t use templates, I’ll make up something new that acts roughly the same. The auto_ptr is the one structure in C++ that undeniably says “owner”. When I receive an object via auto_ptr, I am now the owner. When I return an auto_ptr from a function, I’ve clearly given up ownership.

The recipient of the auto_ptr has to do something with the referenced object, or else it will be deleted when the auto_ptr passes out of scope. If the recipient decided to release the auto_ptr, they can keep a normal pointer or reference in whatever structure pleases them. They can make a copy and delete the original (remember the warning about dangling).

The trick is to remember that 99% of the time, you want to be a borrower, and that any class that is going to hold a borrower’s reference to an object needs an algorithmic guarantee that the referenced object will outlive the reference.

The scary part is for an object to have a large number of long-term borrowers, because there is the constant fear that one might outlive the owner. In that case, you need to hang the auto_ptr on the shelf and go get some bigger magic. You might actually need the smart pointer. I have created reference-counting pointer templates in several projects, which will cause C++ to act more like a garbage-collecting language. I know that there are 3rd-party libraries for garbage-collecting. If I find myself in a situation where there are a number of long-term borrowers, I will definitely move in one of these directions again. It is too important to leave object ownership up to chance or naming convention.

Comments

Leave a response

  1. Avatar
    Fred 28 days later:

    Plug for Boost smart pointers. When I’m on a project where I can use Boost, I never allow naked pointers.

  2. Avatar
    suryamargha19@yahoo.com over 2 years later:

    Hi, That was cooooool…The article ws really written well. I was having trouble to undertstand the owning and aliasing semantics and it cleared my doubt.. Thanks a lot…

    Regs, Surya

  3. Avatar
    Mark Taylor - Crytek over 3 years later:

    The one problem with all such smart pointers is that they commit you to write code in which objects know how to freem themselves. An object that is not responsible for its own memory management is more easily put on the stack, or into arrays, or into some other aggregate.

    I prefer a C style API.

    A* CreateInstanceofA(); void Free(A* ptr);

  4. Avatar
    23@gmail.com over 3 years later:

    For those defective to thomas sabo blog after today’s announcement, the links of london blog will still not a bargain. Now the band says that ” buy Pandora blog ” day duty are being booked for the fourth billet and 2005. The reports is so

  5. Avatar
    Pandora over 4 years later:

    has just told him that hand-washing is too expensive, and he should stop doing it.”

  6. Avatar
    Criminal Records over 4 years later:

    The scary part is for an object to have a large number of long-term borrowers, because there is the constant fear that one might outlive the owner. In that case, you need to hang the auto_ptr on the shelf and go get some bigger magic. You might actually need the smart pointer.

  7. Avatar
    laptop accessories over 4 years later:

    JAY Follow laptop accessories the detail tips below, you can increase the laptop battery life of a year or more. 1. The laptop battery first thing you should care about the

  8. Avatar
    Tenant Screening over 4 years later:

    I have created reference-counting pointer templates in several projects, which will cause C++ to act more like a garbage-collecting language. I know that there are 3rd-party libraries for garbage-collecting.

  9. Avatar
    ipad bag over 4 years later:

    TopCombine Follow ipad bag the detail tips below, you can increase the laptop battery life of a year or more. Game Controllers first thing you should care about the USB Gadgets END!444444444444444444444

  10. Avatar
    mac cosmetics over 4 years later:

    thanks for taking the time in making it and sharing it now everytime someone asks a question related to B&W coloring I will refer them to this list

  11. Avatar
    chanel handbags for sale over 4 years later:

    Very comprehensive, and definitely helpful. is awed

  12. Avatar
    christian louboutin sales over 4 years later:

    Awesome idea for a tutorial list. Am definitely adding to mems to browse as and when.

  13. Avatar
    okey oyunu oyna over 4 years later:

    Thanks so much it is nice article.

    Okey oynamak hiç bu kadar zevkli olmadi. Online ve 3 boyutlu okey oyunu oyna ve turnuvalara sende katil.

  14. Avatar
    christian louboutin shoes on sale over 4 years later:

    Have the christian louboutin patent leather pumps is a happy thing. Here have the most complete kinds of christian louboutin leather platform pumps.

  15. Avatar
    beats by dr dre headphones over 4 years later:

    These beats by dr dre solo are just the same as selling in the franchise store.Or even better.

  16. Avatar
    beats by dre store over 4 years later:

    to vote to thWealthy people: “You suck one, do not look for friends!” 1, Pol.ice: drink?beats by dre sale cheap beats by dre

  17. Avatar
    bagsupplyer over 4 years later:

    Thank you very much.Waiting for update. Fashion designer Men G-star sweaters from China for wholesale at on line store

  18. Avatar
    balmain dresses over 4 years later:

    thanks for share with us

  19. Avatar
    ysbearing over 5 years later:

    Slewing ring is also called slewing bearing, some people called: rotary support, swing support. English Name: slewing bearing or slewing ring bearing or turn table bearing, slewing ring in the real industrial applications is very wide.

  20. Avatar
    iPhone contacts backup over 5 years later:

    It is true.Well. Though I am not a good application developer. And I need do more hard work to improve myself. When I come to here. I know that I have come to the right place to learn something I need. Thanks for your good advice. And I will do the practice as possible as I can. Thanks.

  21. Avatar
    louboutin sales over 5 years later:

    Single Ownership in C++ (intro to auto_ptr) 20 hoo,good article!!I like the post!17

  22. Avatar
    bladeless fans over 5 years later:

    Single Ownership in C++ (intro to auto_ptr) 21 good post171

Comments