std::string::c_str() 可以 return nullptr 吗?

Could std::string::c_str() ever return nullptr?

我在这里和其他资源上阅读了几个主题,但没有找到确切的答案。答案似乎是从不。请确认。


停止。从来没有。如 中所述:

std::string str {nullptr};  // Undefined behavior

所以如果这不会抛出(取决于实现),c_str() 可以 return (char_t*)nullptr.

我相信没有其他方法可以从 c_str() 得到 nullptr。但必须询问 Whosebug 社区才能确定。感谢关注。

没有。由于 c_str returns 指向以 null 结尾的字符数组的指针 p,因此必须存在某个值 i >= 0 使得 p[i] == '[=13=]',因此 p 不能为空。