Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> - C++ objects implicitly have links from parent to child and child to parent. So there's built-in circularity. How does that work?

Can you elaborate? In my understand, the parent/child relation are on the class not the object itself.



A child class can reference fields in the parent, and the parent can call virtual functions in the child.


You mean vtable for inheritance? There's no ownership relation here.


Well, there is: it's easy to trigger unsafe behaviour by calling a virtual method accessing a child class data member (say some std::vector) when in the parent class destructor, as the child sub object will already have been destroyed. Thus it's reasonable to say that there is a bidirectional ownership relationship.


Yes. Rust has safe destructor semantics. C++ does not.

Back references are really hard in Rust. You can do them with Rc, RefCell, and Weak, but there's a lot of run-time checking involved. More static analysis could eliminate most of that run-time checking. .borrow(), .borrow_mut(), and .upgrade().unwrap() panic if they ever fail. So you really want to prove they can't fail. If you can do that, you don't need the run-time checks. In that direction lies the solution to Rust's limited data structure problems.


When in the parent class destructor, the v-table will point toward the parent's v-table not the child's (try it out), so I'm not sure how you'd call a virtual method accessing a child member.


Would it? Or is it undefined? No C++ runtime I know of will generate a new, different vtbl just to switch it out when invoking the non-owning base class destructor on an object. Nor am I familiar with any part of the C++ stnadrd that mandates this behaviour, or even mandates vtbls.


It doesn't create a new vtbl, when invoking the base object destructor it just repoints the current vtable ptr to the base object vtable as first thing:

   https://godbolt.org/z/MKx6oTE63
I can't recite chapter and verse, but I'm pretty sure that's mandated by the standard and it mirrors the behaviour in the constructor.

Or you meant something else?


Of course it would, not a lot would run otherwise. Here is very nice writeup about vtables and constructors: https://shaharmike.com/cpp/vtable-part4/


Section 11.9.5.4 of the C++23 standard describes the observable behaviour.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: