简体   繁体   中英

Why does string::c_str() return a const char* when strings are allocated dynamically?

Why does it return a constant char pointer? The C++11 standard says:

The pointer returned points to the internal array currently used by the string object to store the characters that conform its value.

How can something that is dynamically allocated be constant( const char* )?

In C and C++, const translates more or less to "read only".

So, when something returns a char const * , that doesn't necessarily mean the data it's pointing at is actually const --it just means that the pointer you're receiving only supports reading, not writing, the data it points at.

The string object itself may be able to modify that data--but (at least via the pointer you're receiving) you're not allowed to modify the data directly.

The pointer returned by c_str is declared to point to a const char to prevent modifying the internal string buffer via that pointer.

The string buffer is indeed dynamically allocated, and the pointer returned by c_str is only valid while the string itself does not change. Quoting from cppreference.com :

The pointer obtained from c_str() may be invalidated by:

  • Passing a non-const reference to the string to any standard library function, or

  • Calling non-const member functions on the string, excluding operator[], at(), front(), back(), begin(), rbegin(), end() and rend().

I'm going to interpret the question as why can't you cast it back to a char * and write to it and expect it to work.

The standard library reserves the option to itself to lazy-copy strings in the copy constructor; thus if you wrote to it via the result of c_str() you would potentially write to other strings. As most uses of c_str() would not need to write to the string, dedupling on the call to c_str() would impose too large a penalty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM