字符串文字是数组对象:
typeid("hello").name() // char [6]
这似乎很方便,因为字符串文字(=array)的大小在编译时是已知的。那么为什么没有构造函数来std::string
引用数组呢?
// this would be great
template <int N>
std::string(const char (& array)[N]);
const char * s
相反,有些构造函数采用const char * s, size_t n
或两个InputIterator
s(例如。const char * begin, const char * end
)。所有这些都有缺点;数组被隐式转换为指针并且大小信息丢失,因此使用各种方法将其取回。工作,但越来越疯狂的例子:
// std::string(const char * s) version:
std::string s1("hello"); // calls std::strlen(s) internally
// std::string(const char * s, size_t n) version:
std::string s2("hello", 5); // programmer does std::strlen(s) mentally
std::string s3("hello", sizeof("hello")); // have to repeat string literal
// macro helper to avoid repeating string literal (ugly and dangerous)
#define STRLIT(x) std::string(x, sizeof(x)); // could be a function I guess
std::string s4 = STRLIT("hello"); // not much improvement (and macros are evil)
// std::string(InputIterator begin, InputIterator end) version:
char tmp[] = "hello"; // copy array
std::string s5(&tmp[0], &tmp[sizeof(tmp)]); // so you can reference it twice
// or trust the compiler to return the same address for both literals
std::string s6(&"hello"[0], &"hello"[sizeof("hello")]); // totally crazy