How does adding a private member variable break C++ ABI compatibility?

后端 未结 1 443
名媛妹妹
名媛妹妹 2020-12-30 05:04

The pimpl idiom is commonly used in order to allow changing code in dynamically linked libraries without breaking ABI compatibility and having to recompile all the code that

相关标签:
1条回答
  • 2020-12-30 05:14

    The main problem is that, when you allocate a new instance of a class (either on the stack, or via new), the calling code needs to know the size of the object. If you later change the size of the object (by adding a private member), this increases the size needed; however your callers are still using the old size. So you end up not allocating enough space to hold the object, and the object's constructor then proceeds to corrupt the stack (or heap), because it assumes it has enough space.

    Additionally, if you have any inline member functions, their code (including offsets to member variables) may be inlined into the calling code. If you add private members anywhere other than the end, these offsets will be incorrect, also leading to memory corruption (note: even if you add to the end, the size mismatch is still a problem).

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