任何一个可以帮助解释下面的构造是如何工作是已知的,结构串像文字,其大小在编译时
class StringData {
public:
/**
* Constructs a StringData explicitly, for the case of a literal whose size is known at
* compile time.
*/
struct LiteralTag {};
template<size_t N>
StringData(const char (&val)[N], LiteralTag)
: _data(&val[0]), _size(N-1) {}
private:
const char* _data; // is not guaranted to be null terminated
mutable size_t _size; // 'size' does not include the null terminator
}
为什么不直接使用此构造对象吗?
StringData(const char *c):_data(c){}
完整的源代码可以在这里找到:http://api.mongodb.org/cplusplus/1.7.1/stringdata_8h_source.html
因为那个不设置大小... – chris 2013-03-19 03:03:28
@chris我可以轻松地将大小添加到第二个。为什么不添加_size = strlen(c);在身体里?是否有必要创建如此复杂的构造函数来克服大小? – JiuDong 2013-03-19 03:29:12
虽然分配量很大,但它会节省大量时间,而不是'strlen',它应该遍历每个字符串的末尾 – borisbn 2013-03-19 03:40:09