Boost logo

Boost :

From: Janson R. (mlists.aerostun_at_[hidden])
Date: 2020-07-31 18:02:32


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, [] (lifetime
of objects), [class.cdtor] (ctors and dtors) and []
(storage allocation and deallocation)


> ==================================================================
> 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.

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 [], 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.

Boost list run by bdawes at, gregod at, cpdaniel at, john at