打印空指针未定义行为吗? [英] Is printing a null-pointer Undefined Behavior?
问题描述
当研究此问题的示例代码时,我曾认为这是未定义行为",它阻止了std::cout
的后续使用印刷.但是事实证明,尝试打印空指针会导致std::ios_base::badbit
和std::ios_base::failbit
设置为流状态这是导致其无法运行的真正原因.因此,我现在想知道是否确实 未定义行为(尝试)以打印空指针.所以这是我的问题:
When studying the sample code for this question I had assumed it was Undefined Behaviour which was preventing subsequent uses of std::cout
from printing. But it turns out that attempting to print a null pointer caused std::ios_base::badbit
and std::ios_base::failbit
to be set in its stream state which was the real cause for its being non-operational. Because of this, I am now curious if it really is Undefined Behaviour to (attempt) to print a null-pointer. So here are my questions:
-
打印空指针是否是未定义行为?如果是这样,那么导致流插入的原因是什么?我敢肯定,插入程序很聪明,不会取消引用空指针.
Is it Undefined Behaviour to print a null-pointer? If so, what is it about the stream inserter that would cause this? I'm pretty certain the inserter is smart enough to not dereference a null-pointer.
我还想知道为什么在这种情况下(特别是badbit
)遇到空指针时,插入程序为何设置其错误掩码.为什么不将其视为字符串文字的终止?
I would also like to know why the inserter sets its error mask when encountering a null-pointer in this context (specifically badbit
). Why doesn't it treat it like the termination of a string literal?
我没有Standard方便,到目前为止,我只发现了一个不幸导致死链的消息源.
I don't have a Standard handy, and I only found one source thus far that unfortunately led to a dead link.
推荐答案
basic_ostream
的operator<<(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_ostream
的operator<<(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.
这篇关于打印空指针未定义行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!