Re: delete this; return ret;

Discussion in 'C++' started by Karl Heinz Buchegger, Jun 24, 2003.

  1. Wenjie wrote:
    >
    > Hello,
    >
    > We are into this design: The object will delete
    > itself under some circumstance. It is fine under
    > unitary tests. But I am a little bit worried
    > about the return value after the deletion:
    >
    > class Game {
    > public:
    > //...
    > int gameOver();
    > };
    >
    > int Game::gameOver()
    > {
    > //...
    > delete this;
    > return 100; //LABELED
    > }
    > //...
    >
    > int main()
    > {
    > Game* myGame = new Game();
    > //...
    > int score = myGame->gameOver();
    >
    > //...
    > }
    >
    > In other words, will //LABELED line
    > be executed?


    yes

    > My confusion is that the
    > object should have been destructed at
    > that time.


    It is.
    In C++ an object doesn't hold the executable code, only
    the data. So when you delete an object that doesn't mean
    that somehow the executable code gets wiped off the
    memory. If you think of it: It would be silly if each
    and every object carries with it all the executable
    code for all member functions. 1000 objects then
    would mean, that there are 1000 copies of the gameOver
    function. But this is not the case. The function exists
    in memory only once. The code is shared by all objects
    of type Game.

    So as long as you don't use any member variables or
    call member functions after the delete this, you are
    fine.

    --
    Karl Heinz Buchegger
    Karl Heinz Buchegger, Jun 24, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Unforgiven

    Re: delete this; return ret;

    Unforgiven, Jun 24, 2003, in forum: C++
    Replies:
    0
    Views:
    769
    Unforgiven
    Jun 24, 2003
  2. Karl Heinz Buchegger

    Re: delete this; return ret;

    Karl Heinz Buchegger, Jun 25, 2003, in forum: C++
    Replies:
    0
    Views:
    689
    Karl Heinz Buchegger
    Jun 25, 2003
  3. priyanka
    Replies:
    34
    Views:
    796
    Malcolm
    Jun 4, 2006
  4. metal
    Replies:
    8
    Views:
    493
    Bruno Desthuilliers
    Oct 30, 2009
  5. X X
    Replies:
    4
    Views:
    341
    red floyd
    Jul 19, 2010
Loading...

Share This Page