0

Why behavior like this is allowed?:

class A {
public:
    void print() { cout << ++x; }
private:
    int x = 10;
};

int main() {
    A* ptr;
    int* ptr2;
    {
        A a;
        ptr = &a;

        int b = 10;
        ptr2 = &b;
    }

    ptr->print();
    cout << ++*ptr2;
}

program output: 11 11

Here we are using objects that has already been destroyed. Why program isn't throwing exceptions in this case? Will exception rise the moment program allocate something in place of destroyed objects?

JAJA
  • 40
  • 5
  • 3
    welcome to the world of Undefined Behavior – Alberto Sinigaglia Jun 03 '21 at 01:10
  • [What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/a/367662) – 001 Jun 03 '21 at 01:16
  • *Why program isn't throwing exceptions in this case?* -- Because there are only a few cases where a C++ program is guaranteed to throw an exception, and those places are all mentioned in the C++ standard document (for example `std::vector::at()` will throw an exception). Making mistakes such as what you are making in the code is not one of those places where an exception is thrown, only undefined behavior. – PaulMcKenzie Jun 03 '21 at 01:17
  • Thank you for your answers, now I see why getting an exception here is not a thing. @JohnnyMopp link you provided lands in my bookmarks. – JAJA Jun 03 '21 at 01:29

1 Answers1

0

Why behavior like this is allowed?:

Why do you think that it is allowed? What do you mean by "allowed"?

The behaviour of the shown program is undefined.

Why program isn't throwing exceptions in this case?

Because a program isn't guaranteed to throw exceptions when the behaviour is undefined. Nothing is guaranteed about the behaviour of the program.

Will exception rise the moment program allocate something in place of destroyed objects?

No, there is no such guarantee. There are no guarantees whatsoever.

The cases that may cause an object to be thrown in a well defined program:

  • A throw expression
  • Calling (possibly implicitly) a function that uses the throw expression.
  • dynamic_­cast
  • typeid
  • new expression
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Why is this allowed to be? Because all of the tests required to make sure the programmer hasn't done something stupid would slow the programs of all of the programmers who didn't do anything stupid. You will find some environments will insert checks for common UB into debug builds to help you find errors, but release builds are all about speed. – user4581301 Jun 03 '21 at 01:56