c++ - Changing data ignoring const qualifier -


i have asked related question know undefined behavior.

returning const char* char* , changing data

string _str = "sdfdfsd"; char* pstr = (char*)_str.data(); (int = 0; < isize; i++)     pstr[i] = ::tolower(pstr[i]); 

i had discussion 1 of colleagues this. , told me won't cause problem in scenario ever unless change length of data. if change data keep length same never create problem there no way std::string detect data has been changed. won't cause internal inconsistency either in _str. case?

undefined behavior has been decried much, afraid, , references nasal daemons seem have convinced people more mythical else.

it seems colleague has been desensitized, in order convince need bring him concrete proof of issue. luckily, if have gcc @ hand can done:

#include <iostream> #include <string>  int main() {     std::string const upper = "hello, world!";     std::cout << "upper: " << upper << "\n";      std::string lower = upper;     (char* begin = const_cast<char*>(lower.data()),          * end = begin + lower.size();          begin != end;          ++begin)     {         *begin = std::tolower(*begin);     }     std::cout << "lower: " << lower << "\n";     std::cout << "upper: " << upper << "\n";     return 0; } 

if use gcc, here get:

upper: hello, world! lower: hello, world! upper: hello, world!   // hell ? upper const !!! 

why ? because gcc has historically used copy on write, , since cheated did not detect write , underlying storage array shared.

note: yes, non-conformant c++11, wish had chance work in c++11 though.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -