Is it really a good idea to break encapsulation?

I am just starting to learn about encapsulation, and I stumbled upon two functions used by std :: string, which seem to violate 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 returned pointer points to the internal array currently used by the string object to store characters matching its value.

For someone just learning about OO programming, is it really a good idea to break encapsulation? How about someone more advanced?

Aside, this seems to be different from C ++ 98 behavior. Why do you believe that they made these changes?

Thank you for your time.

+4
source share
3 answers

I stumbled upon two functions used by std :: string, which seem to violate its encapsulation.

Your examples are not a violation of encapsulation rules:

C ++ Programming Language, Fourth Edition, Bjarne Stroustrup:

! 2.5. Function pointer

There is no implicit conversion of a string to char *. This has been tested in many places and found to be error prone. Instead, the standard library provides an explicit function for converting c_str () to const char *.

string::data(). , STL , , std::string. - . , char, , , string char* .

:

?

- , - .

"" , .. .., , , ,

:. . , , , . (, - , ...). , , . , , , 500 , , , . ?

: , , , .

, , , , , , .

: -, , , , - , .

+1

, , , ++ . . c_str , , , undefined, , , ++ .

+3

, , . , , .

string , . - , , , . , , string, . ASCII, UTF-8, , . , std::string, std::string, std::string, . , , , .

API- C, . ( ? , , ASCII/UTF8/UTF16/ .. ). const char *data, , , std::string. .

, , , , - , , . , - .c_str() .c_int(), , , / / , .

, , , , API, /, . , API ++, char * std::string. (, std::string, / , , , , ABI !), "" API , , .

+2
source

All Articles