简体   繁体   English

为什么我的 C++ 程序在使用 NULL 对象时默默退出?

[英]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 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.如果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.

相关问题 当我删除cout语句时,为什么我的C ++程序会因退出代码11而崩溃? - Why does my C++ program crash with exit code 11 when I remove a cout statement? C ++,当我使用这种数组存储数据时为什么我的程序挂起? - C++, Why does my program hangs when I use this kind of array to store data? 为什么我的C ++程序使用的系统时间多于运行时间? - Why does my C++ program use more system time than run time? 为什么当用户从命令行给出浮点数时,我的 C++ 程序会一直冻结? - Why does my C++ program keeps freezing when user gives a float from the command line? 为什么我的程序仅循环2次? (初学者C ++) - Why does my program only loop 2 times? (Beginner C++) 为什么我的程序跳过第一个功能? (初学者C ++) - Why does my program skip the first function? (Beginner C++) 为什么我的C ++程序无法编译(“未定义的引用”)? - Why does my C++ program not compile (“undefined reference”)? 为什么我的C ++程序在一台机器上而不在另一台机器上崩溃? - Why does my C++ program crash on one machine and not on another? 为什么我的C ++程序输出乱码 - Why does my c++ program output garbled code 为什么这个小小的变化会停止我的C ++程序? - Why does this small change halt my C++ program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM