且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打印空指针未定义行为吗?

更新时间:2023-11-10 19:34:22

basic_ostreamoperator<<(basic_ostream<>&, const char*)函数要求char*不为空-它旨在打印指针指向的字符串.因此,将空的char*发送到cout是未定义的行为. (请参见C ++ 11 27.7.3.6.4/3字符插入器功能模板".)

basic_ostream's operator<<(basic_ostream<>&, const char*) function requires that the char* is non-null - it is designed to print the string the pointer points to. So it is undefined behavior to send a null char* to cout. (See C++11 27.7.3.6.4/3 "Character inserter function templates").

但是,basic_ostreamoperator<<(basic_ostream<>&, const void*)函数仅打印指针的值,因此空指针将在该重载下正常工作.

However, basic_ostream's operator<<(basic_ostream<>&, const void*) function simply prints the value of the pointer, so a null pointer will work properly with that overload.