Hacker News new | ask | show | jobs
by eklitzke 1838 days ago
What does it mean that they don't enforce deep immutability? If you have a const pointer or reference you can't call non-const methods or make changes to variables declared without the "mutable" modifier. As you already alluded, if you want to call some non-const methods and then make the object immutable forever you can use an IIFE:

  const auto foo = [&]() {
      Foo x;
      x.call_some_non_const_method();
      x.something_else_non_const();
      return x;
  }();
I don't know what to say about your problems with external libraries taking non-const parameters. Const correctness is one of the most basic things you learn about when you first learn C++, so whether or not you think it's a good system I can't imagine there are going to be many good external libraries that aren't const correct.

I'd also add even if you thought you could enforce this at runtime, in practice it wouldn't really work due to pointer aliasing.

1 comments

By deep immutability, I meant Foo{Bar*} where Bar has further nested structs. It's tedious to have to manually mark every field in the tree as const to achieve deep immutability, which can easily be stripped off with a cast.

What if some of those structs are from libraries and I can't mark their inner fields as const? Yes, most libraries I've used are well tested so I don't need to worry about them modifying my fields but there's no guarantee that I won't.

> I'd also add even if you thought you could enforce this at runtime

I'm well aware this is a hard problem. It was something I frequently discussed with my lab mate who wrote his thesis on this exact topic. I'm simply saying it would be a nice-to-have construct like assertions.