SL.str.1:使用std::string管理字符序列
string correctly handles allocation, ownership, copying, gradual expansion, and offers a variety of useful operations.
string可以正确处理分配,所有权,复制,渐进增长并提供各种有用的操作。
Example(示例)
vector<string> read_until(const string& terminator)
{
vector<string> res;
for (string s; cin >> s && s != terminator; ) // read a word
res.push_back(s);
return res;
}
Note how >> and != are provided for string (as examples of useful operations) and there are no explicit allocations, deallocations, or range checks (string takes care of those).
(作为有用的操作的示例)注意>>和!=是如何提供给string的,代码中也没有显性的内存分配和释放或者内存检查(string会处理好这些)。
In C++17, we might use string_view as the argument, rather than const string& to allow more flexibility to callers:
在C++17中,我们可以使用string_view类型参数,而不是const string&以便为用户提供更多的灵活性。
vector<string> read_until(string_view terminator) // C++17
{
vector<string> res;
for (string s; cin >> s && s != terminator; ) // read a word
res.push_back(s);
return res;
}
Don't use C-style strings for operations that require non-trivial memory management
不要将C风格字符串用于需要一定复杂度的内存管理的操作中。
char* cat(const char* s1, const char* s2) // beware!
// return s1 + '.' + s2
{
int l1 = strlen(s1);
int l2 = strlen(s2);
char* p = (char*) malloc(l1 + l2 + 2);
strcpy(p, s1, l1);
p[l1] = '.';
strcpy(p + l1 + 1, s2, l2);
p[l1 + l2 + 1] = 0;
return p;
}
Did we get that right? Will the caller remember to free() the returned pointer? Will this code pass a security review?
我们做对了么?调用者会记住释放返回的指针么?这段代码可以通过安全评审么?
Note(注意)
Do not assume that string is slower than lower-level techniques without measurement and remember that not all code is performance critical. Don't optimize prematurely
不要不经测算就假定string就会比低水平技术慢,并且需要明白不是所有的代码都对性能敏感。不要过早优化。
Enforcement(实施建议)
???
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slstr1-use-stdstring-to-own-character-sequences