Home > OS >  Can you mutate an object of custom type when it's declared as constant?
Can you mutate an object of custom type when it's declared as constant?

Time:01-26

In our codebase, Pytorch, there are several areas where an object is declared as const but the object's member variables are eventually modified. e.g., see https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Resize.cpp#L29

This particular function here ends up modifying output, which is declared as const. Under what situations can you modify an object declared as const and is there an acceptable practice on whether or not this should be done?

CodePudding user response:

It is doing so through a (eventual) call to TensorBase::unsafeGetTensorImpl which returns TensorBase*, a mutable pointer, even though is declared as const and as such is safe to call in this scenario.

As the method name suggests, this is unsafe.

CodePudding user response:

You can, but you are betraying your users

A lot of times we get hung up on what we can do and/or get away with. But we forget that programming is designed for humans to communicate ideas. And the programming environment is designed to help us do that correctly and succinctly.

So yes, you could, at any time, throw off the constness of your target object(s) and do what you like. If you are lucky no future user will find a way and attempt to pass something that is actually in a section of memory marked as read-only.

But the purpose of marking a thing as “const” is that you (the programmer) personally guarantee the users of a function/method/whatever that it will not attempt to modify the object, for any reason.

To then sneakily modify it behind your users’ collective back, totally outside their expectations, is just plain Wrong™.

Don’t do it.

Consequently, I suggest you recommend fixing your codebase to be correct: remove the consts. It will not break any existing code using it, so that helps if you need to convince anyone to make your interface declare itself truthfully.

EDIT: An “output” object should never be “const” anyway. Functional languages like Haskell, for example, go through a lot of pains to separate mutable output and immutable objects (via Monads, in case you are curious to read more).

  •  Tags:  
  • Related