• tias@discuss.tchncs.de
    link
    fedilink
    arrow-up
    10
    ·
    18 hours ago

    You can’t, not in e.g. Java or C#.

    C++ and Rust are the only languages I know of that do this right.

    • calcopiritus@lemmy.world
      link
      fedilink
      arrow-up
      1
      ·
      3 hours ago

      You can do some kind of RAII in python with the with keyword. Only works for local variables though, where it’s easy to free resources manually

      • tias@discuss.tchncs.de
        link
        fedilink
        arrow-up
        1
        ·
        edit-2
        8 minutes ago

        But if you ever forget the with keyword, you have a leak. With proper RAII the resource acquisition and release is a property of the object’s type and impossible to forget. RAII doesn’t just mean “resource acquisition is initialization”, it also implies “destruction is resource release”.

      • tias@discuss.tchncs.de
        link
        fedilink
        arrow-up
        4
        ·
        14 hours ago

        Maybe you’re thinking of IDisposable with the using keyword. The problem with that is that you have to remember to use it in every call site. Nothing stops a caller from writing var x = new Foo() and walking away.

        • Zarobi@aussie.zone
          link
          fedilink
          English
          arrow-up
          0
          ·
          39 minutes ago

          You can make it a compilation error via configuration of project, but I forget exactly how to do it. Some magic Microsoft thing. I made it an error in my last project and fixed it up