I am just starting to learn about encapsulation, and I stumbled upon two functions used by std::string that seems to break its encapsulation.
Regarding c_str() and data() from http://www.cplusplus.com/reference/string/string/c_str/ and http://www.cplusplus.com/reference/string/string/data/
"The pointer returned points to the internal array currently used by the string object to store the characters that conform its value".
For someone just learning about OO programming, is it ever a good idea to break encapsulation? How about for someone who is more advanced?
As an aside, it seems like this is different behavior from C++98. Why do you believe that they made these changes?
Thanks for your time.
While sometimes utility and backwards compatibility overrides the desire for encapsulation like Mahmoud mentions don't let the C++ standard library be validation for breaking encapsulation lightly. This particular point has been contentious and even a source of bugs within many code bases. The problem with c_str
is that it opens up bad memory corruption by people abusing the returned pointer value or holding on to it for too long after modifying the string which is considered undefined behavior, but neither the compiler nor the runtime environment can enforce that restriction, so in this case the C++ committee chose convenience over safety, and that tradeoff should not be made without considerable justification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With