mardi 26 janvier 2016

const_cast const STL container, is it undefined behavior?

I know that use of const_cast won't introduce undefined behaviour (i.e., it's safe to use), as long as the variable you're const_casting wasn't originally defined as const or if it was originally defined as const you're not modifying it via its const_casted alias.

However, It is also known that most STL containers (e.g., std::vector, std::set), allocate their internal buffers dynamically. Based on this fact I think that is impossible for a const defined std::vector to be placed in read-only memory.

Naturally, if the above holds I come to the assumption that such kind of STL containers even if they're defined as const, e.g.,:

std::vector<int> const v;

const_casting them and altering them via their const_casted alias is legitimate and won't cause any undefined behavior.

Does the above assumption holds or I'm wrong?

Aucun commentaire:

Enregistrer un commentaire