[英]Why can't I construct a string with a NULL char* in C++?
In C++, why does the following code throw a runtime error?在 C++ 中,为什么下面的代码会抛出运行时错误? Could someone explain this for me?有人可以为我解释一下吗?
char* p = NULL;
string str(p);
I tried this in VS2013 and Codeblocks, but both got a runtime error.我在 VS2013 和 Codeblocks 中尝试过这个,但都出现了运行时错误。
The constructor string::string(const char *)
requires that the argument point to the first element of a null-terminated array of characters.构造函数string::string(const char *)
要求参数指向以空字符结尾的字符数组的第一个元素。 You are violating that requirement.您违反了该要求。
For reference, [string.cons]:作为参考,[string.cons]:
basic_string(const charT* s, const Allocator& a = Allocator());
Requires:
s
points to an array of at leasttraits::length(s) + 1
elements ofcharT
.要求:s
指向至少包含traits::length(s) + 1
个charT
元素的charT
。
(It is traits::length(s)
) that requires null termination of the array, see [char.traits.require].) (它是traits::length(s)
)需要数组的空终止,参见 [char.traits.require]。)
The constructor of the string class expects a pointer to a valid string.字符串类的构造函数需要一个指向有效字符串的指针。 And a null-pointer isn't.而空指针不是。 But the run-time library might or might not check whether the given pointer is null.但是运行时库可能会也可能不会检查给定的指针是否为空。 So, in one environment the code might simply crash and in another the run-time library might handle the error in another way, for example by throwing an exception.因此,在一种环境中,代码可能只是崩溃,而在另一种环境中,运行时库可能会以另一种方式处理错误,例如抛出异常。
Note the by注意通过
char* p = NULL;
you have not created an empty string, but a pointer with a value of zero, thus pointing to an illegal address.您没有创建空字符串,而是创建了一个值为 0 的指针,因此指向了一个非法地址。 If you wanted to create a pointer to an empty string you should have written:如果你想创建一个指向空字符串的指针,你应该写:
char* p = "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.