Unexpected output instead of runtime error

后端 未结 2 1330
粉色の甜心
粉色の甜心 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条回答
  •  猫巷女王i
    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

提交回复
热议问题