Hacker News new | ask | show | jobs
by trinovantes 1838 days ago
I wish more languages have the concept of "object/memory freezing" especially at runtime, similar to runtime assertion checks, but without using 3rd party compiler plugins to instrument my code.

C++'s insane "const * const" syntax makes it hard to conceptualize when I just want "create object, do bunch of non trivial stuff, freeze object forever"

1 comments

Why would you want a runtime check if you can have a compile time check?

what is insane about const * const? (although a const unique_ptr<T> is obiously better and propagate_const ist nice) For you usecase if "create object, do bunch of non trivial stuff, freeze object forever" you propably want a IIFE.

Most of the time, factories or IIFE would be sufficient. Sometimes the non trivial stuff is non deterministic, requires other sources of input, or gives up cpu control that makes them insufficient for all use cases.

Also, my problem with const pointers is that they don't enforce deep immutability and can cause all sorts of compilation errors if I try to pass them to non-const functions (usually to external libraries). Then I'd end up type casting my pointers which defeats the purpose of static type checking.

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.

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.