0

I am curious to know the below scenario. I, think, know the explanation to this but want to know if my thought is correct in wider forum. I tested on both g++ and clang++ compiler, and the result is same.

Look at the below code snippet:

class A {
public:
    void test() { cout << "A::test\n"; }
};

int main()
{
    A *ptr;
    ptr->test();
    return 0;
}

The output is A::test.

Why access even the memory is not allocated to the class pointer? My thought: The compiler consider the class pointer type when it reaches ptr->test(); even if there is no memory allocation. This is an undefined behavior.

The proper way is to allocate memory and then delete the allocated memory (shown below).

A *ptr = new A;
ptr->test();
delete ptr;

Or,
Use unique_ptr for self garbage management.

unique_ptr<A> ptr(new A);
ptr->test();

What are your thoughts?

user17732522
  • 53,019
  • 2
  • 56
  • 105
pkthapa
  • 1,029
  • 1
  • 17
  • 27
  • 1
    I am not sure what you expect as answer. You seem to already understand that the first example has undefined behavior and why it often still seems to "work". A question should so broad that it invites opinion-based answers, so "_What are your thoughts?_" doesn't seem specific enough to me. – user17732522 May 04 '22 at 01:37
  • 1
    *What are your thoughts?* -- And when you use different compiler options, and the behavior is different, are you going to research those scenarios also? You see, it quickly gets to be a waste of energy investigating undefined behavior, because it is likely to become a "dog chasing his own tail" scenario. In addition, if you know the code is flawed this way, there is a good chance the compiler also knows this, and will totally remove the code from the final executable. An example is this: `if (this == nullptr)`. The compiler knows that this is a nonsense comparison, and removes it. – PaulMcKenzie May 04 '22 at 01:58

0 Answers0