open-std.org上的这篇data()
论文解释了成员超载的原因。
TL;论文博士:添加了非常量.data()
成员函数 forstd::string
以提高标准库的一致性并帮助 C++ 开发人员编写正确的代码。在调用对其 C 字符串参数没有 const 限定的 C 库函数时,它也很方便。
论文中的一些相关段落:
摘要缺少非常量成员函数
是疏忽还是基于 C++11 之前的语义的有意设计?在任何一种情况下,这种功能的缺乏都会诱使开发人员在几个合法的场景中使用不安全的替代方案。本文主张为std::string 添加一个非常量成员函数,以提高标准库的一致性并帮助 C++ 开发人员编写正确的代码。std::string
.data()
std::string
.data()
用例
C 库有时包含具有 char * 参数的例程。一个例子是Windows APIlpCommandLine
中函数的参数。CreateProcess
因为 的data()
成员std::string
是 const,所以它不能用于使 std::string 对象与 lpCommandLine
参数一起工作。开发人员很想.front()
改用,如下例所示。
std::string programName;
// ...
if( CreateProcess( NULL, &programName.front(), /* etc. */ ) ) {
// etc.
} else {
// handle error
}
请注意,当programName
为空时,programName.front()
表达式会导致未定义的行为。一个临时的空 C 字符串修复了这个错误。
std::string programName;
// ...
if( !programName.empty() ) {
char emptyString[] = {'\0'};
if( CreateProcess( NULL, programName.empty() ? emptyString : &programName.front(), /* etc. */ ) ) {
// etc.
} else {
// handle error
}
}
如果有一个非常量.data()
成员,就像 with 一样std::vector
,正确的代码会很简单。
std::string programName;
// ...
if( !programName.empty() ) {
char emptyString[] = {'\0'};
if( CreateProcess( NULL, programName.data(), /* etc. */ ) ) {
// etc.
} else {
// handle error
}
}
.data() std::string
在调用对其 C 字符串参数没有 const 限定的 C 库函数时,非 const成员函数也很方便。这在较旧的代码和需要与较旧的 C 编译器一起移植的代码中很常见。