gpt4 book ai didi

c++ - 永远不会终止的程序是有效的 C++ 程序吗?

转载 作者:行者123 更新时间:2023-12-02 06:16:51 25 4
gpt4 key购买 nike

程序是否需要终止?换句话说,是一个在技术上永远运行的程序未定义行为?请注意,这与空循环无关。谈论永远做“事情”(即可观察的行为)的程序。

例如像这样的东西:

int main()
{
while (true)
{
try
{
get_input(); // calls IO
process();
put_output(); // calls IO, has observable behavior

// never break, exit, terminate, etc
} catch(...)
{
// ignore all exceptions
// don't (re)throw
// never go out of loop
}
}
}

这更像是一个学术问题,因为根据经验,所有理智的编译器都会为上述类型的程序生成预期的代码(当然假设没有其他 UB 来源)。是的,当然有很多程序永远不会终止(操作系统、嵌入式、服务器)。然而,标准有时很奇怪,因此产生了问题。

<小时/>

切线:许多(某些?)“算法”的定义要求算法必须终止,即一系列永不终止的操作不被视为算法。

<小时/>

切向。停止问题表明不存在一种算法来确定任意程序是否完成输入。然而,对于这个特定的程序,由于没有分支导致退出 main,编译器可以轻松确定该程序永远不会结束。然而,这无关紧要,因为问题是语言律师。

最佳答案

C++ 标准中没有任何内容要求程序或任何给定线程终止。最接近的是 [intro.progress]p1 ,其中表示

The implementation may assume that any thread will eventually do one of the following:

  • terminate,
  • make a call to a library I/O function,
  • perform an access through a volatile glvalue, or
  • perform a synchronization operation or an atomic operation.

[ Note: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven.  — end note ]

只要最终存在一些可观察到的行为,或者只要它在 I/O 操作或另一个阻塞库调用上花费了所有时间,这就不适用,并且该计划是有效的(假设它满足所有其他有效性标准)。

关于c++ - 永远不会终止的程序是有效的 C++ 程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58708623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com