I cannot see the need for auto_ptr?!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jamie Burns

    I cannot see the need for auto_ptr?!

    Hello,

    I realise that I just dont get this, but I cannot see the need for auto_ptr.
    As far as I have read, it means that if you create an object using an
    auto_ptr, instead of a raw pointer, then the object will get cleaned up when
    the method/function ends. Isn't this what happens if you just declare an
    object without using a pointer at all? Aren't these examples the same (I
    know they will not be, but I am hoping someone may explain to me what I am
    missing here!):

    void f()
    {
    T t;
    t.SomeFunc();
    } // cleanup when function ends

    void f()
    {
    auto_ptr<T> pt(new T);
    pt->SomeFunc();
    } // cleanup when function ends

    Wish I could see what is going on here!

    Jamie.


  • lilburne

    #2
    Re: I cannot see the need for auto_ptr?!

    Jamie Burns wrote:
    [color=blue]
    > Hello,
    >
    > I realise that I just dont get this, but I cannot see the need for auto_ptr.
    > As far as I have read, it means that if you create an object using an
    > auto_ptr, instead of a raw pointer, then the object will get cleaned up when
    > the method/function ends. Isn't this what happens if you just declare an
    > object without using a pointer at all? Aren't these examples the same (I
    > know they will not be, but I am hoping someone may explain to me what I am
    > missing here!):
    >
    > void f()
    > {
    > T t;
    > t.SomeFunc();
    > } // cleanup when function ends
    >
    > void f()
    > {
    > auto_ptr<T> pt(new T);
    > pt->SomeFunc();
    > } // cleanup when function ends
    >
    > Wish I could see what is going on here!
    >[/color]

    What is required is that the object T is destructed when it
    is no longer used and the memory it occupied is returned to
    the system. With stack based objects (your first example)
    this happens automatically when the object goes out of
    scope, but with heap based objects (your second example)
    this doesn't occur when a bare pointer goes out of scope.
    auto_ptr being a stack based object gets destroyed
    automatically, and in the process destroys the heap based
    object T that the auto_ptr contains.

    Comment

    • Jamie Burns

      #3
      Re: I cannot see the need for auto_ptr?!

      OK, so maybe I don't get why you wouldn't just allocate T on the stack? Is
      that a bad thing to do? Why go out of your way to allocate on the heap if it
      requires this type of attention to cleanup?

      Jamie.

      "lilburne" <lilburne@godzi lla.net> wrote in message
      news:bmutih$rco 4u$1@ID-203936.news.uni-berlin.de...[color=blue]
      > Jamie Burns wrote:
      >[color=green]
      > > Hello,
      > >
      > > I realise that I just dont get this, but I cannot see the need for[/color][/color]
      auto_ptr.[color=blue][color=green]
      > > As far as I have read, it means that if you create an object using an
      > > auto_ptr, instead of a raw pointer, then the object will get cleaned up[/color][/color]
      when[color=blue][color=green]
      > > the method/function ends. Isn't this what happens if you just declare an
      > > object without using a pointer at all? Aren't these examples the same (I
      > > know they will not be, but I am hoping someone may explain to me what I[/color][/color]
      am[color=blue][color=green]
      > > missing here!):
      > >
      > > void f()
      > > {
      > > T t;
      > > t.SomeFunc();
      > > } // cleanup when function ends
      > >
      > > void f()
      > > {
      > > auto_ptr<T> pt(new T);
      > > pt->SomeFunc();
      > > } // cleanup when function ends
      > >
      > > Wish I could see what is going on here!
      > >[/color]
      >
      > What is required is that the object T is destructed when it
      > is no longer used and the memory it occupied is returned to
      > the system. With stack based objects (your first example)
      > this happens automatically when the object goes out of
      > scope, but with heap based objects (your second example)
      > this doesn't occur when a bare pointer goes out of scope.
      > auto_ptr being a stack based object gets destroyed
      > automatically, and in the process destroys the heap based
      > object T that the auto_ptr contains.
      >[/color]


      Comment

      • Thore B. Karlsen

        #4
        Re: I cannot see the need for auto_ptr?!

        On Sun, 19 Oct 2003 22:00:22 +0100, "Jamie Burns" <sephana@email. com>
        wrote:
        [color=blue]
        >OK, so maybe I don't get why you wouldn't just allocate T on the stack?[/color]

        Because you want it to live longer than it would on the stack.
        [color=blue]
        >Is that a bad thing to do? Why go out of your way to allocate on the heap if
        >it requires this type of attention to cleanup?[/color]

        Because it is very often the right thing to do.

        --
        Be seeing you.

        Comment

        • Jamie Burns

          #5
          Re: I cannot see the need for auto_ptr?!

          But if I want it to live longer, surely I wouldn't be using an auto_ptr in
          the first place (as it won't live past the end of the function that created
          it) ?!

          This is what I cannot grasp.

          In terms of lifetime, T on the stack, and an auto_ptr<T> on the heap are the
          same, no?

          If so, that just leaves "Because it is very often the right thing to do",
          which whilst I am sure is a sincere opinion, doesn't help me to understand.

          :o(

          Jamie.

          "Thore B. Karlsen" <sid@6581.com > wrote in message
          news:9vu5pv4opi tfoa154v3tif2dc pcj25bi6e@4ax.c om...[color=blue]
          > On Sun, 19 Oct 2003 22:00:22 +0100, "Jamie Burns" <sephana@email. com>
          > wrote:
          >[color=green]
          > >OK, so maybe I don't get why you wouldn't just allocate T on the stack?[/color]
          >
          > Because you want it to live longer than it would on the stack.
          >[color=green]
          > >Is that a bad thing to do? Why go out of your way to allocate on the heap[/color][/color]
          if[color=blue][color=green]
          > >it requires this type of attention to cleanup?[/color]
          >
          > Because it is very often the right thing to do.
          >
          > --
          > Be seeing you.[/color]


          Comment

          • lilburne

            #6
            Re: I cannot see the need for auto_ptr?!

            Jamie Burns wrote:
            [color=blue]
            > But if I want it to live longer, surely I wouldn't be using an auto_ptr in
            > the first place (as it won't live past the end of the function that created
            > it) ?![/color]

            Correct in general but you may want to return one, or you
            may have to take ownership of a bare pointer returned from
            some thing else.
            [color=blue]
            > This is what I cannot grasp.[/color]

            Sometimes you have no option but to create something on the
            heap (say the object is very big)


            Comment

            • grejdanospam@pacbell.net

              #7
              Re: I cannot see the need for auto_ptr?!

              On Sun, 19 Oct 2003 21:40:55 +0100, Jamie Burns <sephana@email. com> wrote:
              [color=blue]
              > Hello,
              >
              > I realise that I just dont get this, but I cannot see the need for
              > auto_ptr.
              > As far as I have read, it means that if you create an object using an
              > auto_ptr, instead of a raw pointer, then the object will get cleaned up
              > when
              > the method/function ends. Isn't this what happens if you just declare an
              > object without using a pointer at all? Aren't these examples the same (I
              > know they will not be, but I am hoping someone may explain to me what I
              > am
              > missing here!):
              >
              > void f()
              > {
              > T t;
              > t.SomeFunc();
              > } // cleanup when function ends
              >
              > void f()
              > {
              > auto_ptr<T> pt(new T);
              > pt->SomeFunc();
              > } // cleanup when function ends
              >
              > Wish I could see what is going on here!
              >
              > Jamie.
              >
              >
              >[/color]

              You are right, auto_pointer is unnecessary.
              One reason to use dynamic allocation is to allocate array of the size
              known at the run time. std::vector deals with it.
              Second reason could be to create an object which polymorphic type is known
              at the run time. Then we could use :
              template <class Type> type_dependent_ code(Type *p) {
              Type data;
              data.SomeFunc() ; };
              void f() {
              determine the TYPE;
              type_dependent_ code(static_cas t<TYPE*>(0));
              };


              Returning pointer to dynamically allocated object is not a good idea
              anyway.

              --
              grzegorz

              Comment

              • lilburne

                #8
                Re: I cannot see the need for auto_ptr?!

                grejdanospam@pa cbell.net wrote:
                [color=blue]
                >
                >
                > Returning pointer to dynamically allocated object is not a good idea
                > anyway.
                >[/color]

                Returning large objects on the stack is a worse idea.

                // performance killer
                vector<Point3D> calculate_some_ geometry()
                {

                vector<Point3D> geometry;

                // do something that adds lots of points to geometry

                return geometry;
                }

                Comment

                • Thore B. Karlsen

                  #9
                  Re: I cannot see the need for auto_ptr?!

                  On Sun, 19 Oct 2003 22:20:42 +0100, "Jamie Burns" <sephana@email. com>
                  wrote:
                  [color=blue]
                  >But if I want it to live longer, surely I wouldn't be using an auto_ptr in
                  >the first place (as it won't live past the end of the function that created
                  >it) ?!
                  >
                  >This is what I cannot grasp.
                  >
                  >In terms of lifetime, T on the stack, and an auto_ptr<T> on the heap are the
                  >same, no?[/color]

                  Yes, but you can return the auto_ptr, in effect just returning a pointer
                  instead of a copy-constructed object which might be expensive or (as is
                  often the case) impossible, or just not the right thing to do. Or you
                  can have a big object that is only allocated when it's needed, but whose
                  lifetime is longer than the scope you're in. Or you can take ownership
                  of an existing raw pointer and have auto_ptr wrap it and deal with
                  deallocating it.

                  If you don't understand why it's necessary, don't worry about it. You
                  will immediately see its utility once you start writing programs that
                  are sufficiently complex.

                  --
                  Be seeing you.

                  Comment

                  • grejdanospam@pacbell.net

                    #10
                    Re: I cannot see the need for auto_ptr?!

                    On Sun, 19 Oct 2003 22:58:39 +0100, lilburne <lilburne@godzi lla.net> wrote:
                    [color=blue]
                    > grejdanospam@pa cbell.net wrote:
                    >[color=green]
                    >>
                    >>
                    >> Returning pointer to dynamically allocated object is not a good idea
                    >> anyway.
                    >>[/color]
                    >
                    > Returning large objects on the stack is a worse idea.
                    >
                    > // performance killer
                    > vector<Point3D> calculate_some_ geometry()
                    > {
                    >
                    > vector<Point3D> geometry;
                    >
                    > // do something that adds lots of points to geometry
                    >
                    > return geometry;
                    > }
                    >
                    >[/color]

                    void calculate_some_ geometry(vector <Point3D>& v);

                    --
                    grzegorz

                    Comment

                    • Bob Nelson

                      #11
                      Re: I cannot see the need for auto_ptr?!

                      Jamie Burns <sephana@email. com> wrote:
                      [color=blue]
                      > I realise that I just dont get this, but I cannot see the need for auto_ptr.
                      > As far as I have read, it means that if you create an object using an
                      > auto_ptr, instead of a raw pointer, then the object will get cleaned up when
                      > the method/function ends. Isn't this what happens if you just declare an
                      > object without using a pointer at all? Aren't these examples the same (I
                      > know they will not be, but I am hoping someone may explain to me what I am
                      > missing here!):[/color]

                      The mechanism by which an auto_ptr ``transfers ownership'' to the
                      receiving call site makes it a very worthy addition to a C++ developer's
                      toolchest. (In particular, but realizing that threads are not defined
                      by the C++ language (hence the parens), it makes it easy to create a
                      pointer to an object in a routine that ``hands it off'' to a detached
                      thread).

                      Here's a toy example of the power afforded by auto_ptr. Note that the
                      call site need not be concerned with the destruction...t hat gets
                      handled when ``f()'' goes out of scope:

                      =============== ============ [ cut ] =============== =============== =====

                      #include <cassert>
                      #include <memory>

                      using namespace std;

                      struct C {
                      C(): i(42) {}
                      int i;
                      };

                      static void f(auto_ptr<C> p)
                      {
                      assert(p->i == 42);
                      assert(p.get()) ;
                      }

                      int main()
                      {
                      auto_ptr<C> p(new C);

                      assert(p->i == 42);
                      assert(p.get()) ;
                      f(p);
                      assert(!p.get() );
                      }

                      Comment

                      • lilburne

                        #12
                        Re: I cannot see the need for auto_ptr?!

                        grejdanospam@pa cbell.net wrote:
                        [color=blue][color=green]
                        >>[/color]
                        >
                        > void calculate_some_ geometry(vector <Point3D>& v);
                        >[/color]

                        Prefered solution, but presupposes that the data's final
                        resting place is already determined.

                        Comment

                        • grejdanospam@pacbell.net

                          #13
                          Re: I cannot see the need for auto_ptr?!

                          On Mon, 20 Oct 2003 00:38:02 +0100, lilburne <lilburne@godzi lla.net> wrote:
                          [color=blue]
                          > grejdanospam@pa cbell.net wrote:
                          >[color=green][color=darkred]
                          >>>[/color]
                          >>
                          >> void calculate_some_ geometry(vector <Point3D>& v);
                          >>[/color]
                          >
                          > Prefered solution, but presupposes that the data's final resting place is
                          > already determined.
                          >
                          >[/color]

                          That's what i would do with the big data, wouldn't you ?

                          --
                          grzegorz

                          Comment

                          • grejdanospam@pacbell.net

                            #14
                            Re: I cannot see the need for auto_ptr?!

                            On Sun, 19 Oct 2003 22:50:56 GMT, Bob Nelson <bnelson@nelson be.com> wrote:
                            [color=blue]
                            > Jamie Burns <sephana@email. com> wrote:
                            >[color=green]
                            >> I realise that I just dont get this, but I cannot see the need for
                            >> auto_ptr.
                            >> As far as I have read, it means that if you create an object using an
                            >> auto_ptr, instead of a raw pointer, then the object will get cleaned up
                            >> when
                            >> the method/function ends. Isn't this what happens if you just declare an
                            >> object without using a pointer at all? Aren't these examples the same (I
                            >> know they will not be, but I am hoping someone may explain to me what I
                            >> am
                            >> missing here!):[/color]
                            >
                            > The mechanism by which an auto_ptr ``transfers ownership'' to the
                            > receiving call site makes it a very worthy addition to a C++ developer's
                            > toolchest. (In particular, but realizing that threads are not defined
                            > by the C++ language (hence the parens), it makes it easy to create a
                            > pointer to an object in a routine that ``hands it off'' to a detached
                            > thread).[/color]

                            But the idea of creating an object in a routine that hands it of to a
                            detached thread is not a good idea to start with.
                            Maybe if reference counted but transfering ownership , under threat ,
                            maybe.
                            Point is that the shared resources that are the source of the object
                            are limited. Owning resources that are shared ?
                            this was possible in 16 bit dos, maybe not so bad after all.

                            --
                            grzegorz

                            Comment

                            • Alf P. Steinbach

                              #15
                              Re: I cannot see the need for auto_ptr?!

                              On Sun, 19 Oct 2003 21:40:55 +0100, "Jamie Burns" <sephana@email. com> wrote:
                              [color=blue]
                              >I realise that I just dont get this, but I cannot see the need for auto_ptr.[/color]

                              Ah, well, isn't that in the FAQ?

                              Checking...

                              Nope, not all, but the FAQ does explain the merits of std::auto_ptr in the
                              presence of exceptions,
                              <url: http://www.parashift.c om/c++-faq-lite/exceptions.html #faq-17.4>.

                              Okay, here goes, "std::auto_ ptr for ze novice", by yours truly.

                              std::auto_ptr is currently the only example in the standard library of a
                              "smart pointer":


                              A "smart pointer" is an object that encapsulates a pointer and provides
                              all the operations that the encapsulated pointer has, plus, it provides
                              automatic deallocation.


                              The scheme used by std::auto_ptr is very basic: it transfers _ownership_
                              on assignment and copy construction (the last through a horrible hack).
                              If a std::auto_ptr object goes out of scope or is otherwise destroyed,
                              it will deallocate the object it's got a pointer to if and only it
                              currently owns that object. So as soon as you put a pointer into a
                              std::auto_ptr you know the pointed-to object will be deallocated sooner
                              or later; later, if you keep assigning that std::auto_ptr to other
                              std::auto_ptr's , thus transferring ownership of the object.

                              Now this is very useful for some oft-occurring situations. Say, for example,
                              that you want to return a largish object from a function. One way is

                              LargeObject* foo()
                              {
                              return new LargeObject();
                              }

                              But this is very unsafe, for who's gonna deallocate that object? There's
                              nothing about foo that indicates this. Some novice might write

                              void bar()
                              {
                              LargeObject* p = foo();

                              p->doTheFandango( );
                              }

                              forgetting to deallocate the object, while a programmer with a year or two
                              of experience might write

                              void bar()
                              {
                              LargeObject* p = foo();

                              p->doTheFandango( );
                              delete p;
                              }

                              forgetting that 'doTheFandango' might throw an exception, in which case
                              the object is not deallocated.

                              If, instead, you design 'foo' as


                              std::auto_ptr<L argeObject> foo()
                              {
                              return new LargeObject();
                              }

                              then whoever uses that function has to actively try to _avoid_ proper
                              deallocation in order to mess things up. The most natural is to write
                              client code like


                              void bar()
                              {
                              std::auto_ptr<L argeObject> p = foo();

                              p->doTheFandango( );
                              }

                              where the call to 'foo' transfers ownership up to the local
                              std::auto_ptr in 'bar', which guarantees deallocation even if, as Murphy
                              guarantees will happen, 'doTheFandango' throws an exception.

                              Comment

                              Working...