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?