例如,假设我有
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/