最近学习使用SFML时,在官方网址中,官方在强调Event Loop的重要性,代码如下
#include <SFML/Window.hpp>
int main()
{
sf::Window window(sf::VideoMode(800, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
}
return 0;
}
其中while(window.pollEvent(Event))循环就是事件循环,官方提示如下
A mistake that people often make is to forget the event loop, simply because they don't yet care about handling events (they use real-time inputs instead). Without an event loop, the window will become unresponsive. It is important to note that the event loop has two roles: in addition to providing events to the user, it gives the window a chance to process its internal events too, which is required so that it can react to move or resize user actions.
我认为这个循环完全是不必要的存在,但是存在即合理,我想不清楚这个循环的存在意义,麻烦大家能给一个答案让我死心OMO
事件循环是许多游戏框架中的主要机制,包括 SFML。事件循环是一个非常灵活的机制,通过将事件逐一添加到事件队列中,使事件的时间顺序变得清晰。你从官方摘录下来的话也提到了,没有事件循环,窗口就会变得没有反应。而且事件循环可以处理窗口的内部事件,即调整窗口大小和移动窗口等。
总而言之,事件循环可以提高效率和程序的可维护性,是一个非常重要的编程模型。
如果你理解windows的消息循环,应该自然的就会理解SFML中Event Loop,这不过是个更高维度的封装。
首先,我不太明白你不理解的点,其次,如果你觉得事件循环没有意义,那么,你认为更好的方式是什么?