std :: string :: c_str()能否返回nullptr?

时间:2017-07-23 19:20:34

标签: c++ string c++11 nullptr

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

停止。永远不会。如Why can you assign nullptr to std::string?中所述:

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

因此,如果这不会抛出(取决于实施),c_str()可能会返回(char_t*)nullptr

我认为没有其他方法可以从nullptr获取c_str()。但必须要求StackOverflow社区确定。谢谢你的关注。

1 个答案:

答案 0 :(得分:7)

没有。由于c_str将指针p返回给以null结尾的字符数组,因此必须有一些值i >= 0,以便p[i] == '\0',因此p不能空。