I was hoping someone could clarify what is meant by undefined behavior in C ++.
Technically, “Undefined Behavior” means that the language does not define the semantics for doing such a thing.
In practice, this usually means that it does not , it can break down when your compiler performs optimization or for other reasons. "
What puzzles me is why this works and will modify the original const object , but it does not even give me a warning that this behavior is undefined.
In this particular example, an attempt to modify any non-mutable object may "work" or may overwrite memory that does not belong to the program or belongs to [part] of some other object, since the non-mutable object can be optimized at compile time or can exist in some data segment only for reading in memory.
The factors that can lead to these things are simply too complicated to list. Consider the case of dereferencing an uninitialized pointer (also UB): the "object" you are working with will have some arbitrary memory address, which depends on what value occurred in the memory at the pointer's location; that the “value” potentially depends on previous program calls, previous work in the same program, storage of user input, etc. It just doesn't seem possible to try to rationalize the possible results of calling undefined Behavior, so again, we usually don’t worry and instead say “ don't do this ”.
Which puzzles me, why it works, and will change the original const object , but it won’t even offer me to warn that this message is undefined.
As an additional complication, compilers are not required to diagnose (issue warnings / errors) for undefined Behavior, because the code that causes undefined Behavior does not match the wrong code (i.e., it is obviously illegal), In many cases it is not advisable for the compiler to even detect UB, therefore, this is an area in which the responsibility of the programmer lies with the programmer.
Type of system: - including the existence and semantics of the const keyword - represents the basic protection against writing code that will break; A C ++ programmer should always remember that undermining this system — for example, by breaking const ness — is done at your own peril and risk, and this is usually a bad idea. ™
I can imagine a case where a lack of awareness that a C-style cast could lead to the execution of const_cast might not be noticed.
That's right. With warning levels set high enough, the common sense compiler can warn you about it, but it’s not necessary, and it may not happen. All in all, this is a good reason why C style castes are not approved, but they are still supported for backward compatibility with C. This is just one of those bad things.