为何向ostream传入nullptr会终止向stdout的输出?
问题:输出nullptr后后续std::cout内容不显示的原因
编译环境
$ g++ --version g++ (GCC) 9.2.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ g++ test.cpp -o test -g
测试代码
#include <iostream> int main() { const char * c = nullptr; std::cout << "testing: " << c << std::endl; std::cout << "why does this not print?" << std::endl; return 0; }
运行结果
$ ./test testing: $ echo $? 0
原因分析
向std::cout输出const char*类型的nullptr属于C++标准中的未定义行为,而GCC的实现会将这个操作判定为错误,直接让std::cout进入错误状态(触发failbit)。
一旦流处于错误状态,后续所有的输出操作都会被直接跳过——这就是第二行文本完全没输出、甚至std::endl的换行和刷新都没执行的原因。
程序退出码为0是因为流的错误状态不会自动终止程序,除非你通过std::cout.exceptions()手动设置了对应的异常触发规则。
如果要验证流的错误状态,可以在输出c后添加检查:
std::cout << "testing: " << c << std::endl; if (!std::cout) { std::cerr << "cout已进入错误状态!" << std::endl; }
要避免这个问题,可将空指针转换为void*类型输出,这样会打印指针的地址值(nullptr通常显示为0x0),不会触发流错误:
std::cout << "testing: " << static_cast<void*>(c) << std::endl;
内容的提问来源于stack exchange,提问作者ajoseps
相关产品推荐
相关产品推荐

