它没有在 std::string 中明确列出 constructor doc ,(编辑: 这里的人说我应该引用实际的 cppreference 而不是 cplusplus.com)但显然它有效。这意味着它相当于 strncpy
,不是吗?
它是否有效,因为它首先隐式初始化另一个 std::string
对象,该对象是传入的 const char* string
的拷贝?这是否意味着它会在复制整个字符串时做额外的工作,即使它最终只提取一定长度的子字符串?
此外,这种构造似乎有点像string (const char* s+pos, size_t len)
除了引用文献在这里说如果len大于字符串长度,它会导致未定义的行为
;但在 string (const char* s, size_t pos, size_t len = npos)
中,如果 len 不再通过空终止符,那就没问题了。大概是因为,我猜,这在内部处理 cpp 字符串对象级别的东西,而前者在处理指针。
为什么 C++ 引用文档中没有列出该行为?
我的猜测是它是一种内部复制到 std::string
对象然后应用 string (const string& str, size_t pos, size_t len = npos) 的奇怪组合
到它,所以它不被认为是“标准”。也就是说,我发现这非常有用,当我必须将输入作为 char*
时,虽然我几乎不关心复制整个字符串一次,但我可以逃避做任何 malloc
和 strncpy
我也不想编写代码来分支以确保大小限制 len 不会超出范围。
最佳答案
这是因为构造函数的存在:
std::basic_string( const basic_string& other,
size_type pos,
size_type count = std::basic_string::npos,
const Allocator& alloc = Allocator() );
const char *
可隐式转换为 std::basic_string
,因此当您编写(例如)std 时,会在所述转换后调用上述构造函数: :string s {"abc", 1, 2};
为了解决您的效率问题,从 char *
到 std::basic_string
的隐式转换涉及临时构造,所以是的,字符串被复制。
关于c++ - 为什么 string (const char* s, size_t pos, size_t len = npos) 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564732/