What is this supposed to do?

Discussion in 'C++' started by MiniDisc_2k2, Jul 12, 2003.

  1. MiniDisc_2k2

    MiniDisc_2k2 Guest

    I was writing a class and came up to something that I needed to do. I needed
    the class to delete itself inside a function. I realized that this is
    illegal, and thought of a way around it. Later, out of curiosity, I tried
    this.

    class A
    {
    public:
    int var;
    void Delete();
    };

    int main()
    {
    A a;
    a.Delete();
    return (0);
    }

    void A::Delete()
    {
    delete this;
    }

    It compiled correctly. At runtime, however, I got an assertation failure (I
    believe that's a compiler specific feature) and then hit a hard-coded
    breakpoint. That was, AFAIK, at delete this. When setting it in non-debug
    mode (optimized and takes out all assertation failures), it just hits the
    breakpoint. If I were to run the program outside of the debugger, nothing
    happens (just a blank screen). What is supposed to happen? I doubt this is
    standardized but if it is what paragraph is it in and what is the compiler
    supposed to do. Don't you think there should be some kind of warning the
    compiler generates for this?

    I realize that the this pointer is only a A * const so technically its
    legally deleted, but it just doesn't make sense to be deleting this. Why
    aren't compilers smarter than they are?

    No warnings at highest warning level.
    --
    MiniDisc_2k2
    MiniDisc_2k2, Jul 12, 2003
    #1
    1. Advertising

  2. MiniDisc_2k2 wrote:
    [...]
    > Why aren't compilers smarter than they are?


    Because

    int main() {
    A & a = *new A;
    a.Delete();
    }

    is just fine.

    regards,
    alexander.
    Alexander Terekhov, Jul 12, 2003
    #2
    1. Advertising

  3. MiniDisc_2k2

    Stephen Howe Guest

    > Why aren't compilers smarter than they are?

    Because they cannot always spot programmers shooting themselves in the foot.

    Stephen Howe
    Stephen Howe, Jul 13, 2003
    #3
    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. ThunderMusic

    How I'm I supposed to use string tables?

    ThunderMusic, Oct 15, 2004, in forum: ASP .Net
    Replies:
    1
    Views:
    444
    John Saunders
    Oct 15, 2004
  2. Simon Harvey
    Replies:
    5
    Views:
    437
    Scott M.
    Nov 16, 2003
  3. Jan Nielsen
    Replies:
    7
    Views:
    511
    Jan Nielsen
    Feb 8, 2005
  4. Replies:
    3
    Views:
    1,504
  5. ibiza
    Replies:
    2
    Views:
    1,985
    ibiza
    Jan 26, 2006
Loading...

Share This Page