CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 25
  1. #1
    Join Date
    Dec 2004
    Posts
    6

    Arrow Smart Pointer Question.

    When is it advantageous to use smart pointer? &
    When it is disadvantageous to use smart pointers?

    It would be good if you can provide me with an example which can explain me both the above suitations.

    I appreciate your effort.

    Thanks in advance,
    Amish.

  2. #2
    Join Date
    Jun 2002
    Location
    Moscow, Russia.
    Posts
    2,176

    Re: Smart Pointer Question.

    Smart pointer can delete object, pointer to which it contains, you don't need to write delete code in destructor every time you add an object by pointer to your class definition (if that class owns that object) and you don't need to check if the object can be deleted and when it should be deleted if this object is not owned by any class. You can pass "copy" of class with some kind of smart pointer (I don't know it it still can be named "smart pointer"), creating another smart pointer as a copy, ang getting read only access to the same object and octually copying it when change is required ("delayed copy", like unix fork, CString in MFC). You can implement all this object managment control, that's it.
    "Programs must be written for people to read, and only incidentally for machines to execute."

  3. #3
    Join Date
    Nov 2004
    Posts
    13

    Re: Smart Pointer Question.

    Quote Originally Posted by Amish79
    When is it advantageous to use smart pointer? &
    When it is disadvantageous to use smart pointers?

    It would be good if you can provide me with an example which can explain me both the above suitations.

    I appreciate your effort.

    Thanks in advance,
    Amish.
    I tried o search the net for yuo an example, didn't know how it should work cause i am also slow in programming.
    Code:
     class sp
      {
           public:
               int del;
               sp* operator ->() { return this;};
      };
    
      int main()
      {
           sp t;
           cout << t->del;
      }

  4. #4
    Join Date
    May 2004
    Location
    Norway
    Posts
    655

    Re: Smart Pointer Question.

    Quote Originally Posted by Hediea
    I tried o search the net for yuo an example, didn't know how it should work cause i am also slow in programming.
    That's no smart-pointer. In fact, I'm not sure what that is supposed to be. Looks like an example of operator -> overloading.

    Anyhoo... A smart pointer (like for instance std::auto_ptr or boost::shared_ptr) can for example be of great help when using dynamically allocated memory, while keeping the code exception safe. Consider the following example:
    Code:
    try
        {
        int* ptr = new int;
        throw 0;
        }
    catch(int ex)
        {}
    Here the pointer to the memory allocated by new will be lost, and you have a memory leak. By using a smart pointer instead, the deallocation will be handeled automatically, and no memory leaks occur. Like so:
    Code:
    try
        {
        std::auto_ptr<int> ptr = new int;
        throw 0;
        }
    catch(int ex)
        {}
    Reference counted smart pointers like boost::shared_ptr, can also be useful when multiple objects need to have a reference to the same object, and the destruction order of these objects is not obvious.

    But even though they seem cool and the temptation to "go Java" (Use new all over the place, in combination with smart pointers) is great, you should be absolutely sure that a smart pointer, or more specifically dynamically allocated memory, is really what you need before you use them. Only use dynamically allocated memory if you have a really compelling reason to do so. Otherwise make do with the stack, and the standard containers.
    Insert entertaining phrase here

  5. #5
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Smart Pointer Question.

    Quote Originally Posted by wien
    Code:
    try
        {
        std::auto_ptr<int> ptr = new int;
        throw 0;
        }
    catch(int ex)
        {}
    Well...it will rather be
    Code:
    try
        {
        std::auto_ptr<int> ptr(new int);
        throw 0;
        }
    catch(int ex)
        {}
    The standard smart pointer does not allow initialization with an ordinary pointer using assignment.

  6. #6
    Join Date
    May 2004
    Location
    Norway
    Posts
    655

    Re: Smart Pointer Question.

    Woops.. Right you are sir!
    Insert entertaining phrase here

  7. #7
    Join Date
    Sep 2004
    Posts
    519

    Re: Smart Pointer Question.

    The purpose of almost all smart pointers are to help manage object lifetimes.

    Common smart pointers are:

    std::auto_ptr
    CComPtr
    CComQIPtr
    _com_ptr_t
    boost::shared_ptr
    boost::intrusive_ptr
    boost::scoped_ptr
    Loki::SmartPtr

    And the list goes on.

    They are same but different so to say. They are all same in the way that they all try to help you manage object lifetimes but they are different in that they fit for different situations.

    Loki::SmartPtr is the one-size-fits-all attempt by Andrei Alexandrescu.

    Although implicitly given by what wien said I thought I just point out that it's not only in the presence of exceptions that you can get problem with memory leaks when not using smart pointers.

    Consider:
    Code:
    void f( int const action )
    {
        int * l_ptr(new int(3));
    
        if( action == 0 )
        {
            return;    // memory leak
        }
        else if( action == 1 )
        {
            throw std::runtime_error("error");    // memory leak
        }
        else if( action == 2 )
        {
            l_ptr = new int(4); // memory leak
        }
    
        delete l_ptr;
    }
    Of course, when you write the code you know how it's supposed to be used but then the maintenance programmer comes in and he/she has to apply a quick fix. He/she might then not be aware on how the life-time in your application is handled and might introduce memory leaks.

    One might think that using single point of return plus try...catch is enough to deal with memory management without smart pointer but exceptions can occur in the darnest of players (consider http://www.gotw.ca/gotw/020.htm) and it can be quite easy to miss a place.

    By using a smart pointer it guarantees that the pointee destructor will be called when the smart pointer goes out of scope.

    So smart pointers helps with object lifetimes. That's all well and good.

    The problem of many smart pointers implementations is that they desperatly try to look as a ordinary plain pointers which can be confusing because a smart pointer is _not_ a plain pointer. Common mistake by smart pointer implementations is that they overload operator & to mimic the plain pointer (CComPtr and CComQIPtr has been notorius for this). But this also makes these smart pointers incompatible with standard containers (which requires a operator & to behave like it defined in the standard). Also many smart pointers (again CComPtr and CComQIPtr) allows implicit conversion to the pointee type which has created many memory leaks over the years. It's all well intended but the road to heck is paved with good intentions.

    Also when using smart pointers the pointee class destructor must _not_ throw exceptions. This is very important!

    Consider this:
    Code:
    struct x
    {
        ~x()
        {
            throw std::runtime_error("error");
        }
    };
    
    void f()
    {
        std::auto_ptr<x> const l_ptr(new x());
        throw std::runime_error("error"); // here exit(0) will be called
    }
    So at the second throw the whole program terminates. This is according to the standard (to be honest I don't have the standard before so I don't know if this is a hard fact). This is because when reaching the second throw an exception is placed on the "stack" (not sure of the exact wording here). std::auto_ptr goes out of scope and ~x() is called. Then a new exception is thrown but there is already one "active". This is illegal and the c++ runtime shall terminate the app.

    Can be suprising and hard to find.


    So drawback of smart pointers are:
    1. They are not plain pointers even if many smart pointers tries very hard to look like one.
    2. The destructor of the pointee type must not throw.
    3. Some smart pointers are incompatible with the standard containers (but then the plain pointers never really were compatible either)


    There are more but I'm just not smart enough right now to think of more and the post is long enough already.

    The big question is then:

    Is it worth it to use smart pointers.

    And my answer is:
    Yes!

    Always, always use smart pointers. Get used to using smart pointers and scope guards. Feel comfortable with smart pointers and use smart pointers of good quality such as boost::shared_ptr (and the rest of the boost smart pointers) or Loki::SmartPtr.

    Hope this helps

    PS. Lot of warning have been made around std::auto_ptr and it's correct that you should understand what std::auto_ptr is intended for but std::auto_ptr is one of the best smart pointers ever made. Sometimes it's _exactly_ what you want. The problem with std::auto_ptr is that it's shipped with STL but it can't be used in the standard containers => confusing.
    Last edited by marten_range; January 6th, 2005 at 05:09 PM. Reason: Correction

  8. #8
    Join Date
    May 2004
    Location
    Norway
    Posts
    655

    Re: Smart Pointer Question.

    Quote Originally Posted by marten_range
    Also when using smart pointers the pointee class destructor must _not_ throw exceptions. This is very important!
    This is in fact something that is good to keep as a rule of thumb all the time. You can get yourself into the same kind of mess even if you don't use smart pointers:
    Code:
    struct x
    {
        ~x()
        {
            throw std::runtime_error("error");
        }
    };
    
    void f()
    {
        x an_x;
        throw std::runime_error("error"); // just as bad...
    }
    Insert entertaining phrase here

  9. #9
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    Re: Smart Pointer Question.

    In fact, go one further: no destructor should ever be allowed to throw an exception. Destructors that throw are evil and are the cause of buggy programs, system crashes and chicken pox. ( )
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


  10. #10
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Re: Smart Pointer Question.

    Doesn't the C++ standard state that exceptions can't be thrown from destructors?
    Kevin Hall

  11. #11
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Smart Pointer Question.

    Quote Originally Posted by KevinHall
    Doesn't the C++ standard state that exceptions can't be thrown from destructors?
    No...not really...it says in 15.3.2:
    [Note: If a destructor called during stack unwinding exits with an exception, terminate is called (15.5.1). So destructors should generally catch exceptions and not let them propagate out of the destructor. —end note]
    IIRC correctly the standard does not say explicitly that destructors aren't allowed to throw in the common sense...

  12. #12
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Re: Smart Pointer Question.

    I'll interpret that as:

    One should not allow exceptions to escape a destructor or else terminate will be called.
    That's a pretty strong discouragement there!
    Last edited by KevinHall; January 7th, 2005 at 11:10 AM.
    Kevin Hall

  13. #13
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Smart Pointer Question.

    [QUOTE=KevinHall]I'll interpret that as:

    [QUOTE]One should not allow exceptions to escape a destructor or else terminate will be called.

    That's a pretty strong discouragement there!
    Well...I do not disagree....destructors actually should not throw anything...however, it is not completely prohibited by the standard (or at least I did not find it yet)...

  14. #14
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Re: Smart Pointer Question.

    Even though the standard doesn't explicitly say one should not allow exceptions to be thrown from destructors, that's how people should interpret the standard. Calling terminate does indicate that your program won't continue working as otherwise expected!

    Let's face the facts, when writing a destructor, people don't usually wrap the entire thing in a try/catch statement. I know I only do it when I think an exception is possible -- and that's on a good day when I remember to think about such things. So I believe the standardization comittee did the right thing here. They provided a controlled way to handle something people should not allow to happen (but that people will too often inadvertently allow to happen), rather than saying the behavior is undefined.
    Kevin Hall

  15. #15
    Join Date
    Oct 2004
    Location
    Long Beach, CA
    Posts
    179

    Re: Smart Pointer Question.

    What an instrusive_ptr? What do all the other smart_ptrs do? And who would name their namespaces "boost" and "Loki"?
    The nerds will rule over the common folk. The geeks will rule over the nerds. The supergeeks will rule over the geeks. The hackers will rule over the supergeeks. The superhackers will rule over the hackers. Mwhahaha; I'll rule you all!!!

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured