Does the created object matter or not
Yes. If the object was not created const , then no matter what you do, const_cast will be safe. Just a bad idea (because you donβt know at all which object was not const created).
is this pointer safe from undefined behavior as it is only marked as const for this function?
This is a wrong question, but the fact is that until you try to modify the const object, you are safe. This means that const_cast itself const_cast completely legal and well defined, but if items.sort() changes the material (and we must assume that it does), then this operation leads to UB.
Finally, although you tried to hush up this point in your question, the practicality of this is actually fundamental to the scenario: it is very difficult to guarantee, even in this seemingly concrete case, that the code is safe. Therefore, do not do this. Despite your attempts to abstract it for the purposes of this issue, I cannot stress this.
source share