delete this;

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martin Vorbrodt

    delete this;

    some butthole asked me an interview question:

    can you delete "this" pointer in a member function of a class, like this:

    class C {
    public:
    void foo() { delete this; }
    };

    my answer was... undefined behavior, maybe? object kills itself and frees
    it's own memory, not a good thing in my opinion.

    the guy tried to convince me that it's a common practice to "reload the
    object", and that this delete would not actually free memory, only call
    destructor(s).

    now, i know C++ pretty darn well, but I'm not the all mighty guru... yet.

    so, am I stupid, or was he full of shit?

    Thanx


  • W Marsh

    #2
    Re: delete this;

    On Tue, 18 Apr 2006 10:12:03 -0400, "Martin Vorbrodt"
    <mvorbrodt@pocz ta.onet.pl> wrote:
    [color=blue]
    >some butthole asked me an interview question:
    >
    >can you delete "this" pointer in a member function of a class, like this:
    >
    >class C {
    >public:
    > void foo() { delete this; }
    >};
    >
    >my answer was... undefined behavior, maybe? object kills itself and frees
    >it's own memory, not a good thing in my opinion.
    >
    >the guy tried to convince me that it's a common practice to "reload the
    >object", and that this delete would not actually free memory, only call
    >destructor(s ).
    >
    >now, i know C++ pretty darn well, but I'm not the all mighty guru... yet.
    >
    >so, am I stupid, or was he full of shit?
    >
    >Thanx
    >[/color]


    Comment

    • Scott McPhillips [MVP]

      #3
      Re: delete this;

      Martin Vorbrodt wrote:[color=blue]
      > some butthole asked me an interview question:
      >
      > can you delete "this" pointer in a member function of a class, like this:
      >
      > class C {
      > public:
      > void foo() { delete this; }
      > };
      >
      > my answer was... undefined behavior, maybe? object kills itself and frees
      > it's own memory, not a good thing in my opinion.
      >
      > the guy tried to convince me that it's a common practice to "reload the
      > object", and that this delete would not actually free memory, only call
      > destructor(s).
      >
      > now, i know C++ pretty darn well, but I'm not the all mighty guru... yet.
      >
      > so, am I stupid, or was he full of shit?
      >
      > Thanx
      >
      >[/color]

      You're both wrong. It is a perfectly legitimate thing to do. It works,
      it does execute the destructor, and does free the memory.

      --
      Scott McPhillips [VC++ MVP]

      Comment

      • Sumit Rajan

        #4
        Re: delete this;


        Martin Vorbrodt wrote:[color=blue]
        > some butthole asked me an interview question:
        >
        > can you delete "this" pointer in a member function of a class, like this:
        >
        > class C {
        > public:
        > void foo() { delete this; }
        > };
        >
        > my answer was... undefined behavior, maybe? object kills itself and frees
        > it's own memory, not a good thing in my opinion.
        >
        > the guy tried to convince me that it's a common practice to "reload the
        > object", and that this delete would not actually free memory, only call
        > destructor(s).
        >[/color]



        Regards,
        Sumit.

        Comment

        • Rolf Magnus

          #5
          Re: delete this;

          Martin Vorbrodt wrote:
          [color=blue]
          > some butthole asked me an interview question:
          >
          > can you delete "this" pointer in a member function of a class, like this:
          >
          > class C {
          > public:
          > void foo() { delete this; }
          > };
          >
          > my answer was... undefined behavior, maybe?[/color]

          It depends on how the object was created. The behaivor is well-defined if
          the object was created with operator new. If it's an automatic or static
          objec, the behavior is undefined.
          [color=blue]
          > object kills itself and frees it's own memory, not a good thing in my
          > opinion.[/color]

          Maybe, but that wasn't the question, as I see it.
          [color=blue]
          > the guy tried to convince me that it's a common practice to "reload the
          > object", and that this delete would not actually free memory, only call
          > destructor(s).[/color]

          Well, that's wrong. Unless you give it a null pointer (in which case it does
          nothing) or a pointer that didn't come from new (in which case, the
          behavior is undefined), delete always frees memory. I have no idea
          what "reload the object" means. Sometimes, an explicit destructor call and
          placement new are used in operator=.

          Comment

          • al pacino

            #6
            Re: delete this;

            hi,
            hey same kind of question was asked to me too!
            he asked me if we delete ' this '
            in destrcutor what will happen?
            i.e
            class foo{
            public:
            //
            ~foo()
            {
            delete this;
            }
            };
            i think this wud result in recursive calls to destructor and stack wud
            overflow

            Comment

            • Noah Roberts

              #7
              Re: delete this;


              Martin Vorbrodt wrote:
              [color=blue]
              > the guy tried to convince me that it's a common practice to "reload the
              > object", and that this delete would not actually free memory, only call
              > destructor(s).[/color]

              Yeah, many times the person interviewing doesn't know shit.

              Comment

              • Kai

                #8
                Re: delete this;

                Hi,

                Actually, 'delete this;' is legal. The compiler doesn't mind, and would
                really delete 'this'. But it's stupid under most situation. see the
                following from


                Title: RE: [ProgSoc] delete self in c++[color=blue]
                > Yeah it's okay to do this .. it's most often used inside
                > the constructor to destroy the object if the object itself
                > isnt valid.[/color]

                Generally speaking, I'd recommend against using "delete this" in code.
                The main problem is that the object can only be created via "new". If
                the object is declared "auto" (i.e. not a pointer or reference) and
                "delete this" is called it will fail because "this" was not allocated
                with new and the program will crash. If you really want to use "delete
                this" in your own code, make the destructor protected, preventing other
                classes from deleting the object and causing a compiler error if an
                auto variable of this class is ever declared.

                If you want to use in it a constructor, I'd recommend against it for
                the above reason and also because the calling function has no way of
                knowing whether the object encountered an error - calling one of the
                object's functions will result in a crash. The object fails to
                instantiate itself will have to modify some form of global variable
                such as errno, SetLastError(), IErrorInfo, etc, which, although
                acceptable, is hardly ideal.

                A much better way to report an error in an object's constructor is to
                use a static "factory" function to encapsulate the construct. E.g.
                static Dog* Dog::CreateDog( int legs) which can return a NULL pointer on
                an error.

                Alternatively, the constructor could throw an exception. Don't worry
                about memory leaks, ANSI-compliant compilers should automatically
                deallocate the object with calling the constructor if a newed object
                throws an exception in its constructor. Check your compiler doco for
                this.

                The only situation I've seen "delete this" where I consider it an
                acceptable use is the the thread or window classes from MFC. The
                intention with these classes is to instantiate them, remove all
                references to them and let the objects manages their own lifespans.
                [color=blue]
                > Also a good idea to check for null after any member function
                > that could cause the object to be destroyed.[/color]

                I haven't got ARM (or a similar tome) handly but I suspect that
                modifying "this" in a member funcion is illegal. Either way, changing
                "this" in a member function will not affect the value of the pointer
                the function was called through. E.g.

                void zero_ptr(char* s)
                {
                // This line only changes the local version of s.
                s = NULL;
                }

                ....

                char *s = "Hello, world!";
                zero_ptr(s);
                printf(s); // Shows "Hello, world!"

                Anthony Langsworth
                Software Developer
                Computing Edge
                mailto:anthonyl @nospam.computi ngedge.com.au

                Comment

                • Noah Roberts

                  #9
                  Re: delete this;


                  Kai wrote:[color=blue]
                  > Hi,
                  >
                  > Actually, 'delete this;' is legal. The compiler doesn't mind, and would
                  > really delete 'this'. But it's stupid under most situation. see the
                  > following from
                  > http://www.progsoc.uts.edu.au/lists/.../msg00010.html
                  >
                  > Title: RE: [ProgSoc] delete self in c++[color=green]
                  > > Yeah it's okay to do this .. it's most often used inside
                  > > the constructor to destroy the object if the object itself
                  > > isnt valid.[/color]
                  >
                  > Generally speaking, I'd recommend against using "delete this" in code.
                  > The main problem is that the object can only be created via "new". If
                  > the object is declared "auto" (i.e. not a pointer or reference) and
                  > "delete this" is called it will fail because "this" was not allocated
                  > with new and the program will crash. If you really want to use "delete
                  > this" in your own code, make the destructor protected, preventing other
                  > classes from deleting the object and causing a compiler error if an
                  > auto variable of this class is ever declared.[/color]

                  You would also want to privatize constructors and implement static
                  factory methods to be sure the object is always created with new.

                  Comment

                  • Alf P. Steinbach

                    #10
                    Re: delete this;

                    * Noah Roberts:[color=blue]
                    > * Kai:[color=green]
                    >> If you really want to use "delete
                    >> this" in your own code, make the destructor protected, preventing other
                    >> classes from deleting the object and causing a compiler error if an
                    >> auto variable of this class is ever declared.[/color]
                    >
                    > You would also want to privatize constructors and implement static
                    > factory methods to be sure the object is always created with new.[/color]

                    No, that's an /alternative/ to making the destructor protected (or private).

                    It is IMO generally an inferior alternative.

                    See section 1.3.3 of my little introduction to pointers at <url:
                    http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf>, which
                    also, in section 1.3.5, discusses how to in-practice disable direct use
                    of new, e.g. for an object that must assume it's managed via a smart
                    pointer of some particular kind.


                    --
                    A: Because it messes up the order in which people normally read text.
                    Q: Why is it such a bad thing?
                    A: Top-posting.
                    Q: What is the most annoying thing on usenet and in e-mail?

                    Comment

                    • tedu

                      #11
                      Re: delete this;

                      Rolf Magnus wrote:[color=blue]
                      > what "reload the object" means. Sometimes, an explicit destructor call and
                      > placement new are used in operator=.[/color]

                      does this have any advantage over creating init() and destroy() member
                      functions?

                      Comment

                      • Rolf Magnus

                        #12
                        Re: delete this;

                        tedu wrote:
                        [color=blue]
                        > Rolf Magnus wrote:[color=green]
                        >> what "reload the object" means. Sometimes, an explicit destructor call
                        >> and placement new are used in operator=.[/color]
                        >
                        > does this have any advantage over creating init() and destroy() member
                        > functions?[/color]

                        Not sure if that could be seen as an advantage, but you can initialize
                        reference and const members in the constructor, but not in an init()
                        function. Hmm, actually, I have used that so that I can have a reference
                        member and still also an operator= that can change that reference.

                        Comment

                        • sillyemperor

                          #13
                          Re: delete this;

                          delete this; is very useful when you have to release a object created
                          in a DLL.

                          Comment

                          • Tom

                            #14
                            Re: delete this;

                            It is legal, but I don't like it. I guess it is used when this object
                            need control its life by itself. In most cases, its life is controlled
                            by others. Or, the object is allocated in heap, but I want it to be
                            released automatically.

                            For the objects in DLL, I like to define a corresponding smart pointer
                            in DLL to release it (not template, it doesn't work).

                            Comment

                            • Martin Jørgensen

                              #15
                              Re: delete this;

                              Martin Vorbrodt wrote:
                              -snip-

                              In the topic line you wrote that I should delete your message. I can't......

                              My newsreader complaints about: "This message does not appear to be from
                              you. You may only cancel your own posts, not those made by others."


                              LOL :-)


                              Best regards / Med venlig hilsen
                              Martin Jørgensen

                              --
                              ---------------------------------------------------------------------------
                              Home of Martin Jørgensen - http://www.martinjoergensen.dk

                              Comment

                              Working...