在 C++ 中打印空字符串是否可观察行为?
在 C++03 标准可观察行为 (1.9/6) 中包括调用库 I/O 函数。现在我有这段代码:
printf( "" );
它正式调用库 I/O 函数,但没有任何效果。
这是可观察到的行为吗?编译器允许消除它吗?
In C++03 Standard observable behavior (1.9/6) includes calls to library I/O functions. Now I have this code:
printf( "" );
which is formally a call to a library I/O function but has no effect.
Is it observable behavior? Is the compiler allowed to eliminate it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果
sync_with_stdio
为true
,则当然可以观察到。如果是这样,printf("")
会强制与std::cout
输出同步,刷新先前缓冲的输出。It's certainly observable if
sync_with_stdio
istrue
. When that's true,printf("")
forces synchronization withstd::cout
output, flushing previously buffered output.输出变得无效,这是可以观察到的
关于sync_with_...的观点也非常相关
It would observable
The point made about sync_with_... is also very relevant
我非常怀疑这一点,因为如果操作系统在调用
printf
的线程阻塞 I/O 时选择上下文切换,那么在多线程编程中该行为可能会变得更加明显。在这种情况下,如果结果取决于线程的交错方式,那么它肯定会产生影响。
I highly doubt it, since the behavior might become more highly visible in multithreaded programming if the OS chooses to context switch when the thread invoking
printf
blocks for I/O.In that case, it will definitely have an effect if the results depend on how the threads is interleaved.
理论上,您的 C 库可以按照根据时间刷新缓冲区的方式编写。在这种情况下,打印空字符串可能会导致刷新,从而产生可见的效果。
In theory, you C library can be written in a way that flushes the buffer based on time. In that case, printing of empty string can result in a flush, thus producing a visible effect.
当然,这具有可观察的行为 - 它必须使用底层文件描述符生成对 write() 系统调用的调用。进行系统调用是非常容易观察到的行为。
考虑一个极端的例子,内核中的文件描述符可能由设备驱动程序提供服务,每次调用写文件操作时都会发出警报声(好吧,我承认有点人为的例子:-)...
Of course this has observable behavior - it must generate a call to write() system call with the underlying file descriptor. Making a system call is very observable behavior.
Consider as an extreme example that the file descriptor in the kernel may be serviced by a device driver that sounds siren every time it's write file operation is called (OK, somewhat of an artificial example, I'll admit :-) ...