Unexpected output instead of runtime error

后端 未结 2 1316
粉色の甜心
粉色の甜心 2020-12-22 10:47

It might be obvious for who knows the background magic, but I could not understand how below code is giving correct output. I expected a runtime error. Please help.

相关标签:
2条回答
  • 2020-12-22 11:39

    There is no magic - your code has undefined behavior. In your code you do not access ptr which is implicitly passed to print() as this pointer, that is why no error happen.

    It may happen in several other cases:

    • Accessing fields of a instance. It will require to read memory *(this + field_offset) which will cause runtime error.

    • Accessing virtual methods. Implementations known to me use vtable to do that, which is usually stored as first pointer in object space, so pointer to vtable would be same as this, so: vtable = *this

    • Other cases, depending on compiler and platform

    NOTE: type conversion is omitted from examples with this

    0 讨论(0)
  • 2020-12-22 11:39

    a::print is a not a virtual method, hence it is just a normal function that has an extra argument to receive the this pointer. Since the method never uses the this pointer, the fact that it is uninitialized doesn't turn into a memory access error or other failure. Declaring a::print static will still compile in this case since it doesn't use the this pointer. Declaring a::print virtual or accessing this inside the method will likely lead to the program crashing, at least under some circumstances.

    The behavior is still undefined and it is an ill-formed program, but as it stands now it is very likely to work deterministically on most systems. In general C++ does not give runtime errors for such cases, but if you compile with e.g. "clang++ -Wall" a warning indicating the uninitialized variable will be given. (And there are tools such as clang's asan which will go further in diagnosing such errors.)

    0 讨论(0)
提交回复
热议问题