Dalla documentazione del StringPiece class in Chromium's source code:Ci sono motivi per cui l'idioma StringPiece/StringRef non è più popolare?
// 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.
Esempio di utilizzo:
void foo(StringPiece const & str) // Pass by ref. is probably not needed
{
// str has same interface of const std::string
}
int main()
{
string bar("bar");
foo(bar); // OK, no mem. alloc.
// No mem. alloc. either, would be if arg. of "foo" was std::string
foo("baz");
}
Questo mi sembra un'ottimizzazione così importante ed evidente che non riesco a capire il motivo per cui non è più diffuso, e perché una classe simile a StringPiece non è già nello standard.
Ci sono motivi per cui non dovrei sostituire l'uso dei parametri string
e char*
nel mio codice con questa classe? C'è qualcosa di simile già nelle librerie standard C++?
UPDATE. Ho appreso che la fonte di LLVM utilizza un concetto simile: la classe StringRef.
Mi piace questa idea teorica. Mi chiedo quanto possa essere confuso nella pratica senza "allenamento". – jmucchiello
Vecchio post, ma per i futuri lettori dovrebbe notare che è stato proposto: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3442.html –