Is this code legal?
class Base1 {
};
class Base2 {
public:
virtual ~Base2() {
if (!dynamic_cast<Base1*>(this))
std::cout << "aaaa" << std::endl;
}
Base2() {
}
};
class MyClass: public Base1, public Base2 {
public:
MyClass() {
}
virtual ~MyClass() {
std::cout << "bbb" << std::endl;
}
};
int main() {
MyClass s;
return 0;
}
I see both prints but I should see only one. I guess the dynamic cast is wrong. Is it possible to make a check of this kind?
Maybe I found the solution myself, the reply is no it's not possible:
From bullet 6 of cppreference.com documentation:
When dynamic_cast is used in a constructor or a destructor (directly or indirectly), and expression refers to the object that's currently under construction/destruction, the object is considered to be the most derived object. If new-type is not a pointer or reference to the constructor's/destructor's own class or one of its bases, the behavior is undefined.
See also [class.cdtor]/6 of the standard.
Since I'm casting to Base1 in Base2 destructor, this behavior is undefined.
I agree with @j6t's answer, but here is an expanded reasoning with standard references.
The special behavior of dynamic_cast
for objects under construction and destruction is described by [class.cdtor]/5 of the C++17 standard (final draft) and equivalently by previous standard versions.
In particular it says:
When a
dynamic_cast
is used [...] in a destructor, [...], if the operand of thedynamic_cast
refers to the object under construction or destruction, this object is considered to be a most derived object that has the type of the [...] destructor's class. If the operand of thedynamic_cast
refers to the object under [...] destruction and the static type of the operand is not a pointer to or object of the [...] destructor's own class or one of its bases, the dynamic_cast results in undefined behavior.
The undefined behavior does not apply here, since the operand is the expression this
, which trivially has the type of a pointer to the destructor's own class since it appears in the destructor itself.
However, the first sentence states that the dynamic_cast
will behave as if *this
was a most derived object of type Base2
and therefore the cast to Base1
can never succeed, because Base2
is not derived from Base1
, and dynamic_cast<Base1*>(this)
will always return a null pointer, resulting in the behavior you are seeing.
cppreference.com states that the undefined behavior happens if the destination type of the cast is not the type of the destructor's class or one of its bases, rather than having this apply to the operands type. I think that is just a mistake. Probably the mention of "new-type" in bullet point 6 was supposed to say "expression", which would make it match my interpretation above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With