简体   繁体   English

为什么我不能在 C++ 中构造一个带有 NULL char* 的字符串?

[英]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 least traits::length(s) + 1 elements of charT .要求: s指向至少包含traits::length(s) + 1charT元素的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.

相关问题 为什么我不能用C ++中的单个char构造一个std :: string? - Why can't i construct a std::string from a single char in C++? C ++:为什么不能使用初始化程序char foo []将字符串转换为C字符串? - C++: Why can't I convert a string to C-string with an initializer char foo[]? 为什么我不能在C ++中用'char'而不是'string'方法使用这种方法? - Why can't I use this approach in C++ with 'char' instead of a 'string' approach? C ++:为什么我不能用sprintf打印const char *? - C++ : Why I can't print a const char* with sprintf? 为什么我不能从 char* 构造 wstring - Why I can't construct a wstring from char* 如何在 c++ 中构造带有嵌入 NULL 字符的 BSTR? - How can i construct BSTR with embedded NULL character in c++? 为什么在Turbo C ++中不能在二进制文件中写入全长字符串(char []) - Why can't write full length string (char[]) in a binary file in Turbo C++ 为什么我不能将字符指针传递给 lambda。 C++ 入门 ex13.44 - why i can't pass a char pointer to lambda. C++ Primer ex13.44 为什么我不能更改 C++ 中的多维 char 数组的值? - Why can't I change the value of a multidimensional char array in C++? C ++ std :: string和NULL const char * - C++ std::string and NULL const char*
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM