C ++切片导致泄漏/未定义的行为/崩溃 [英] C++ slicing causing leak / undefined behavior / crash
问题描述
有什么C ++对象切片效应的例子可以导致未定义的行为,内存泄漏或崩溃在其他正确的代码集?例如,当类 A
和 B
(继承自 A
)是正确和健全的,但调用 void f(A a)
可以引起讨厌的事情。
Is there any example of the C++ object slicing effect which can cause undefined behavior, memory leak or crash in an otherwise correct set of code? For example when class A
and B
(inherited from A
) are correct and sound, but calling a void f(A a)
demonstrably causes nasty things.
需要形成一个测试问题。目标是使用示例代码片段知道参与者是否知道切片现象,其正确性不能是意见问题。
It is needed for forming a test question. The goal is to know if the participant is aware of the slicing phenomenon or not, using an example code snippet whose correctness must not be a matter of opinion.
推荐答案
如果 A
确实是正确和健全,则切片(复制基础子对象)是明确定义的,你提到的问题。如果你期望副本的行为像 B
。
If A
is indeed "correct and sound", then slicing (copying the base sub-object) is well-defined and will not cause any of the problems you mention. The only problem it will cause is unexpected behaviour, if you expect the copy to behave like B
.
如果 A
无法正确复制,则切片将导致复制该类型对象时出现的任何问题。例如,如果它有一个析构函数删除一个由对象持有的指针,并且复制创建一个新的指针指向同一个事物,那么当两个析构函数删除同一个指针时,你会得到未定义的行为。这不是切片本身的问题,而是切片对象的无效复制语义。
If A
is not correctly copyable, then slicing will cause whatever problems arise from copying objects of that type. For example, if it has a destructor which deletes a pointer held by object, and copying creates a new pointer to the same thing, then you will get undefined behaviour when both destructors delete the same pointer. This isn't a problem with slicing as such, but with invalid copy semantics of the sliced object.
这篇关于C ++切片导致泄漏/未定义的行为/崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!