Understanding ~Copyable lifetime for scope-based instrumentation (Probes)

i believe when it comes to ~Copyable structs at least this is incorrect. non-copyable structs have 'lexical lifetimes' which are well defined. this thread may be of interest, and i'm basing this assertion primarily on what Andy said here:


i believe this is an implementation artifact of the particular pattern you're using where the probe is never given a name. if you name the variable you should see the behavior you expect where its deinit runs at the end of scope:

func atExit() {
  let p = ScopeProbe("...")
  // do stuff ...
  // deinit runs here
}

awkwardly, if you never use the variable, this will generate an unused variable warning, so if you want to eliminate that you'll also need a use.

IIUC this would be a bug, since the purpose of lexical lifetimes is to anchor lifetimes to the corresponding lexical scope. do you have an example that reproduces this behavior?


in terms of more ergonomic options – the class-based approach with defer is decent (though perhaps less performant). you may want to look into a macro (and maybe a function body macro).

3 Likes