Destructor called while object is still alive

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Fri Oct 23 19:14:38 UTC 2020


On Friday, 23 October 2020 at 17:47:34 UTC, Steven Schveighoffer 
wrote:
> And when are those called? When the lifetime of the *object* is 
> over, not the lifetime of the pointer to the object.

But the owning pointer is keeping the object alive.

A gc pointer is keeping the object alive, and is keeping it alive 
throughout its own lifetime. So yes, the lifetime of the object 
is supposed be at least as long as the owning pointer. And the 
lifetime lasts till the end of the scope. If there is a 
sideeffect then it should be considered to be _live_ until the 
end of the scope.

With the GC semantics you don't get a guarantee for when it will 
be destructed, but you should have strong guarantees for how long 
the lifetime at least can be expected to be.

Ideally you would also have guarantees for eventual destruction 
(i.e. that all objects are destroyed before the program 
terminates). With precise GC sans union, you should be able to 
get that.


> My point was that C++ doesn't have class references, they have 
> class pointers, which is akin to D class references.

Well, "reference" and "pointer" are two words for the same thing, 
although D has some syntactical and semantic restrictions on 
class references.

That is pretty irrelevant though, as D class references with GC 
are owning pointers

C++ have owning pointers named unique_ptr and shared_ptr. Naked 
pointers are borrowing pointers, or for manual management. Forget 
about the mechanisms, conceptually that is the case.


> I mean, if I compile this code for C++, does it store the 
> pointer on the stack?
>
> void foo()
> {
>    SomeClass* ptr = new SomeClass();
>    ... // bunch of other code that never uses ptr
> }
>
> C++ doesn't have automatic management using pointers. So the 
> answer is, the optimizer might just not store `ptr`. Just like 
> it doesn't happen in D.

But C++ compilers don't provide a GC, and naked pointers are not 
owning pointers.


>> _all_ GC pointers are conceptually owning pointers. They have 
>> to stay live throughout the whole scope.
>
> It doesn't have to even have a pointer if it's never used.

But a destructor with a side effect IS usage, and it should never 
be executed when there is a conceptually live pointer pointing to 
the object.

It is very simple, really.





More information about the Digitalmars-d mailing list