c++ - 当我用 0 初始化 std::string 时发生了什么?

标签 c++

例如,假设我有
std::string str = 0;

是否将 0 转换为 const char*?
当它传递给构造函数时,它是否被转换为 char* 然后转换为 const char*?

我知道将 char* 初始化为 0 是未定义的行为,据我所知,const char* 也是如此,但我不明白将 0 传递给std::string 构造函数。
编辑:我错了。

最佳答案

你猜对了。

如果我们看例如this std::string constructor reference我们可以看到唯一合适的构造函数是数字 5。因此您的定义等于

std::string str = std::string(0);

如引用文献中所述:

The behavior is undefined if s does not point at an array of at least Traits::length(s)+1 elements of CharT, including the case when s is a null pointer.

[强调我的]

是的,它从确实是 UB 的空指针构造了一个 std::string

关于c++ - 当我用 0 初始化 std::string 时发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48557012/

相关文章:

c++ - 如果 new 抛出 std::bad_alloc 是否会将指针设置为 NULL?

c++ - 带有 ctest "Unexpected format: "错误的 googletest

c++ - 加入线程时的性能问题

c++ - "expression must be an l-value or function designator"取地址时出错

c++ - GTest 参数化测试从数组或类似文件中解压值参数

c++ - printf double 最多可显示 n 位小数,但根据需要不能更多

c++ - 为什么 C++ 程序员应该尽量减少 'new' 的使用?

c++ - 使用嵌套的 boost::binds

c++ - 在 C++ 中将重写的类方法作为链调用

c++ - 降噪OpenCV皮肤检测样本