从Chromium的源代码中的StringPiece类的文档:
// A string-like object that points to a sized piece of memory.
//
// Functions or methods may use const StringPiece& parameters to accept either
// a "const char*" or a "string" value that will be implicitly converted to
// a StringPiece.
//
// Systematic usage of StringPiece is encouraged as it will reduce unnecessary
// conversions from "const char*" to "string" and back again.
Run Code Online (Sandbox Code Playgroud)
使用示例:
void foo(StringPiece const & str) // Pass by ref. …Run Code Online (Sandbox Code Playgroud) 我的问题与在C++中使用"s"后缀有关?
使用"s"后缀的代码示例:
auto hello = "Hello!"s; // a std::string
Run Code Online (Sandbox Code Playgroud)
同样可以写成:
auto hello = std::string{"Hello!"};
Run Code Online (Sandbox Code Playgroud)
我能够在网上找到"s"后缀应该用于最小化错误并澄清我们在代码中的意图.
因此,使用"s"后缀仅仅是为了代码的读者?或者还有其他优势吗?
I have C++ code that investigates a BIG string and matches lots of substrings. As much as possible, I avoid constructing std::strings, by encoding substrings like this:
char* buffer, size_t bufferSize
Run Code Online (Sandbox Code Playgroud)
At some point, however, I'd like to look up a substring in one of these:
std::unordered_map<std::string, Info> stringToInfo = {...
Run Code Online (Sandbox Code Playgroud)
So, to do that, I go:
stringToInfo.find(std::string(buffer, bufferSize))
Run Code Online (Sandbox Code Playgroud)
That constructs a std::string for the sole purpose of the lookup.
I feel like there's an optimization I could do here, …
我们知道编译器可以重用相同的常量字符串文字来有效地节省内存.对于编译器,此优化是可选的.
const char *s1 = "HELLO";
const char *s2 = "HELLO";
Run Code Online (Sandbox Code Playgroud)
s1并且s2可以有相同的地址.它们在许多编译器中具有相同的地址.例如,两者都指向地址0x409044.
好.
在我看来,问题是,为什么不std::string尝试具有相同的优势?并且它不会试图包围std::string该地址.
const std::string ss1("HELLO");
const std::string ss2("HELLO");
cout << (void*) ss1.c_str() << endl;
cout << (void*) ss2.c_str() << endl;
Run Code Online (Sandbox Code Playgroud)
ss1并ss2有两个不同的地址.
这在技术上是不可能的吗?被语言禁止?或者标准库的实现开发人员不想要它?