Greetings, On 31/07/2020 18:51, 逸霖 杨 via Boost wrote:
After the destructor call, the object no longer exists, regardless of whether the memory it used to be placed in is freed or not. ===================================== This is true as a concept, but when we overload delete operator for global or for just one class, we write “free(ptr)” inside that overloaded function (at least MS’ implementation of C++ works like this). Which means, it’s practically separated-able: destructor called and free() called. And if we separate the two stages, we can get something that we can not achieve before, just like get a clean reference decreasing method, and free all effected objects all together.
You seem to be missing the fact that dtors are special functions by standard, and dtors inevitably *end* the lifetime of an object of the abstract machine. I suggest you read [basic.memobj]; in particular, [basic.life] (lifetime of objects), [class.cdtor] (ctors and dtors) and [basic.stc.dynamic] (storage allocation and deallocation) (https://eel.is/c++draft/basic.memobj) (https://eel.is/c++draft/basic.life) (https://eel.is/c++draft/class.cdtor) (https://eel.is/c++draft/basic.stc.dynamic)
================================================================== Case 1:
struct A { unsigned int x = 0u;
~A() { x = 0xBAADF00D; } };
rcgc_shared_ptr< A > p1; { rcgc_shared_ptr< A > p2(new A()); p1 = p2; std::cout << p1->x << std::endl; } std::cout << p1->x << std::endl; // (1)
The above is a bug because (1) accesses the object A after its destruction. If A::x was, say a unique_ptr, it would be null or pointing to already freed memory. ====================== Why would we assign x with a useful value in destructors ?
Users will do what users do: do something you do not expect them to do
The thing is in reality, calling destructor is not same as freeing memory.
True Invoking the dtor will end the object's lifetime Freeing memory will release the allocated storage where the object lived on before it was destroyed
Memory is still containing valid data if no one messes with it Attempting to access the contents of an object after its lifetime has been ended is undefined behavior as per [basic.life.6.2], so the bytes found at the allocated storage are considered to contain invalid data, regardless of whether they contain what you expect or not during execution.