For a while now I’ve been working with a C++ project (Envoy), and sometimes I need to contribute to it, so my C++ skills have gone from “nonexistent” to “really minimal”. I’ve learned what an initializer list is and that a method starting with ~ is a destructor. I almost know what an lvalue and an rvalue are but not quite.

But the other day when writing some C++ code I figured out something exciting about how to use destructors that I hadn’t realized! (the tl;dr of this post for people who know C++ is “julia finally understands what RAII is and that it is useful” :))

what’s a destructor?

C++ has objects. When an C++ object goes out of scope, the compiler inserts a call to its destructor. 

So if you have some code like

function do_thing() {
  Thing x{}; // this calls the Thing constructor
  return 2;
}

there will be a call to x’s destructor at the end of the do_thing function. so the code c++ generates looks something like:

  • make new thing
  • call the new thing’s destructor
  • return 2

Read more at Julia Evans blog

Click Here!