How to "dispose of" a string when using @live analysis?

Dukc ajieskola at gmail.com
Fri Aug 29 20:50:00 UTC 2025


On Friday, 29 August 2025 at 17:13:21 UTC, Renato Athaydes wrote:
> How do I dispose of the string?

```D
static void* hackPtr;

// Use whenever you want to artificially end lifetime of a live 
variable
// Note that this can't be @live
void leak(T)(T x)
{   // Otherwise the compiler will infer `scope` for x,
     // defeating the purpose.
     if(false) hackPtr = &x;
}

@live void show(scope ref string s) {
   import std.stdio;
   writeln(s);
}

@live void main()
{
     auto s = "foo bar";
     show(s);
     show(s);
     //Since it's GC-allocated, "leaking" is how we "free" it in 
any case.
     leak(s);
}
```

Now, of course the problem is that you could use this `leak` to 
also "free" a `malloc`ed pointer, in which case it would 
literally be a memory leak. But at least you're doing it 
explicitly so you hopefully have a bit better change to spot 
yourself doing it than without `@live`.

Note that if you do all your allocation with the GC, there's no 
point in using `@live`. Well, many, me included, are of the 
opinion it's not worth it even if you don't but I'm still happy 
to see you test-driving the feature - it's always possible I'm 
wrong!


More information about the Digitalmars-d-learn mailing list