为什么`std::stringstr(nullptr)`和`std::stringstr=nullptr`是错误的?有人可以详细解释原因吗?

为什么std::string str(nullptr)std::string str=nullptr是错误的?有人可以详细解释原因吗?

回答

此类示例之所以能够编译,是因为存在一个std::string(const char*)用于接受以空字符结尾的字符串的构造函数,这是在 C 中存储字符串的标准版本。此外,数组急切地衰减为指针,以允许诸如此类的代码std::string("Ahoj")进行编译。

这是错误的,因为构造函数需要一个有效的以空字符结尾的字符串,尽管该示例可以编译,但它的行为是未定义的。

同样地std::string str(0);将工作和未定义过因为它被用来作为预C ++ 11版本的字面零隐式转换为指针nullptr- NULL

编辑:
我最初声称std::logic_error会被抛出,@François Andrieux 纠正了我。

  • It is Undefined Behavior. It may throw `std::logic_error` if the implementation chooses to handle that case, but it might not.

以上是为什么`std::stringstr(nullptr)`和`std::stringstr=nullptr`是错误的?有人可以详细解释原因吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>