On 06/10/2015 10:16 AM, Norbert Lange wrote:
Thanks for all the answers, now lets get to the next level =) I seen this code from one of my colleagues, and wonder wether this is valid C++: ~CMyclass() { foo(this); } To quote the standard: "The lifetime of an object of type T ends when: * if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or * the storage which the object occupies is reused or released." So you are passing a pointer to an undead object, I can expect this could yield interesting results in some contexts, but since you still have to access the object members during the destruction there isnt much a compiler could mess up? But I`d be interested what should/could happen if derived destructors already did their work, and foo tries to use RTTI (dynamic_cast, typeid). I suspect this is undefined behaviour anyway given that these could throw, and similarly dangerous as accessing virtual functions that might have overrides in the derived classes.
It's perfectly valid and very common. You shouldn't access this after destruction is complete, but calling foo() during the destructor is fine.