我花了一段时间才弄清楚为什么一些 cout 输出似乎消失在以太中。罪魁祸首:
std::cout<< "This line shows up just fine" << std::endl;
const char* some_string = a_function_that_returns_null();
if (some_string == 0)
std::cout<< "Let's check the value of some_string: " << some_string << std::endl;
std::cout<< "This line and any cout output afterwards will not show up" << std::endl;
上面代码段的输出将是:
This line shows up just fine
Let's check the value of some_string:
因此,将 NULL 输入 cout 之后将禁用所有输出。为什么?以及如何解决?
这不会一直发生 - 具有相同代码的同事会获得所有预期的输出。如果您想知道为什么我不能用 if 语句阻止将 NULL 输入 cout:我正在一个大型代码库中工作,不知道还会发生这种情况!我所知道的是我提出的 cout 声明从未出现过。
更多信息:
a_function_that_returns_null()实际上是getenv("HOST")。我通过命令行检查echo $HOST了 HOST 变量是否为空。如果我这样做export HOST=(bash 风味),输出就在那里。getenv在我修改 HOST 变量之前,我不知道 HOST 变量最初包含什么,也不知道最初返回什么;我只知道(some_string == 0)是真的。