The reason why the data()
member got an overload is explained in this paper at open-std.org.
TL;DR of the paper: The non-const .data()
member function for std::string
was added to improve uniformity in the standard library and to help C++ developers write correct code. It is also convenient when calling a C-library function that doesn't have const qualification on its C-string parameters.
Some relevant passages from the paper:
Abstract
Is std::string
's lack of a non-const .data()
member function an oversight or an intentional design based on pre-C++11 std::string
semantics? In either case, this lack of functionality tempts developers to use unsafe alternatives in several legitimate scenarios. This paper argues for the addition of a non-const .data()
member function for std::string to improve uniformity in the standard library and to help C++ developers write correct code.
Use Cases
C libraries occasionally include routines that have char * parameters. One example is the lpCommandLine
parameter of the CreateProcess
function in the Windows API. Because the data()
member of std::string
is const, it cannot be used to make std::string objects work with the lpCommandLine
parameter. Developers are tempted to use .front()
instead, as in the following example.
std::string programName;
// ...
if( CreateProcess( NULL, &programName.front(), /* etc. */ ) ) {
// etc.
} else {
// handle error
}
Note that when programName
is empty, the programName.front()
expression causes undefined behavior. A temporary empty C-string fixes the bug.
std::string programName;
// ...
if( !programName.empty() ) {
char emptyString[] = {'\0'};
if( CreateProcess( NULL, programName.empty() ? emptyString : &programName.front(), /* etc. */ ) ) {
// etc.
} else {
// handle error
}
}
If there were a non-const .data()
member, as there is with std::vector
, the correct code would be straightforward.
std::string programName;
// ...
if( !programName.empty() ) {
char emptyString[] = {'\0'};
if( CreateProcess( NULL, programName.data(), /* etc. */ ) ) {
// etc.
} else {
// handle error
}
}
A non-const .data() std::string
member function is also convenient when calling a C-library function that doesn't have const qualification on its C-string parameters. This is common in older codes and those that need to be portable with older C compilers.
c_str
being null terminated, while astd::string
may contain a null in the middle and I'd expect alsodata()
to return just the raw buffer (whether it contains null in the middle or not)data()
got an overload, whilec_str()
did not? I mean we made them homogeneous in C++11, and now we differentiate again, why? These kind of questions are not answered in the duplicate. However, the answers here provide insight to my question!