The as_const
function returns a Proxy
wrapping the passed-in argument. This proxy attempts to prevent all modifications to the underlying object. The difference between this and using Object.freeze
is that the latter makes the object itself immutable, while as_const
simply prevents direct changes to the object via a specific reference to the object. Additionally, as_const
prevents changes to any object that is referenced through the proxy (i.e. as_const(foo).bar.data = 5
is equivalent to as_const(foo.bar).data = 5
and will throw an exception).
In C++ terms, Object.freeze
is akin to instantiating a const Object
, whereas the result of as_const
is a const Object&
and the original object can still be modified elsewhere.
This idea is leaky enough that I would recommend against using it. If you need functionality like this, prefer a language that offers it reliably as a built-in feature.