[英]Why does my C++ program silently exit when a use a NULL object?
string n = NULL;
cout << "blah: " << n << " foo!" << endl; // never printed
cout << "BLAH" << endl; // never printed
cerr << "FOO" << endl; // never printed
I understand assigning or appending something to NULL is not right.我了解将某些内容分配或附加到 NULL 是不正确的。 But silently dying is not good either.但默默地死去也不好。 How should I handle / debug those situations?我应该如何处理/调试这些情况? And why is the program dying?为什么程序会死?
Your program is free to do whatever the implementation of std::string
you have choses to.您的程序可以随意执行您选择的std::string
实现。 std::string
has a constructor taking a const char* s
. std::string
有一个采用const char* s
的构造const char* s
。 However, this involves:然而,这涉及:
Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by
s
.使用s
指向的以空字符结尾的字符串的副本初始化内容来构造字符串。 The length of the string is determined by the first null character.字符串的长度由第一个空字符决定。 The behavior is undefined ifs
does not point at an array of at leastTraits::length(s)+1
elements ofCharT
, including the case when s is a null pointer.如果s
不指向CharT
至少Traits::length(s)+1
元素的数组,则行为未定义,包括 s 是空指针的情况。(emphasis mine) (强调我的)
Via cppreference通过cppreference
You should just leave n
uninitialized instead, assigning it to NULL in C++11 can lead to undefined behavior.您应该只保留n
未初始化,在 C++11 中将其分配给 NULL 会导致未定义的行为。 There should not be an instance in which you need to assign to NULL.不应存在需要分配给 NULL 的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.