English 中文(简体)
如何经营无限的 lo? [复制]
原标题:How to run an infinite loop? [duplicate]

I want to run some code over and over again basically forever, but I don t want my computer to run out of memory or something like that. So I was wondering how i could do that in c++? I did this.

for (int i = 0; i <= 2; i++) {
    if (i == 1) {i = 0;}
    //My code here
}

我很想知道这是否会给我的计算机造成某种坏?

最佳回答
while(true)
{
    //Your code here
}
问题回答

如果您选择<>forsyntax:

for ( ; ; ) {
    // do stuff.
}

如果你在不释放记忆的情况下分配记忆,则不会造成你的电脑失传。

有一些共同的撰写方式。

for (;;) {
   // do something over an over again
}

while (true) {
   // do something over an over again
}

独一无二的预案本身并没有使该方案摆脱记忆。 但是,如果你分配记忆和忘记去处理,<>>将造成记忆泄露。 鉴于以下法律是正确的:

YourClass* p;
for (;;) {
    p = new YourClass();    // every time the loop runs, a new instance of the class is created
    // [do something useful with the object]
    delete p;   // clean-up: deallocate the object.
}

但这将造成记忆泄露:

YourClass* p;
for (;;) {
    p = new YourClass();    // every time the loop runs, a new instance of the class is created
    // [do something useful with the object]
    // oups... forgot to deallocate the object.
}

如果你知道如何管理他们,那么无限的洛波斯就非常大。 即使有一个无限的通道,你仍然希望有一个可能的撤离条件。 如果你设计了无限的通道,说明根据数据集不可能从该通道中撤出,那么最安全的事情就是跟踪你的申请对象及其现状的事例,以及当国家改变退出时,任何穿过任何透的无限通道都会受到测试,如果能够这样做,将自动退出,以防止你计算机被hang到你需要做硬 re或关闭的地方。 有理由确保,随着这一事件的启动,你的所有记忆都将得到清理。 现在,如果你有多个平行或同步运行的路面,并且由点子或事件触发点清单管理,那么每座路方仍需要时间才能离开,取决于你指定身为CRITICAL_的哪里。 部分。

class Application {
public:
    enum ApplicationState {
        APPLICATION_RUNNING = 0,
        APPLICATION_PAUSED,  // Out of Focus or Paused If In A Timed Situation
        APPLICATION_EXIT,
    };
private:
    // Member Variables Such As Window Handle, Time Etc.,
    ApplicationState m_state;
public:
    Application();
    // virtual ~Application(); // Default Okay - Use Virtual If Using Inheritance
    ApplicationState getState() const { return m_state; }

    bool start() { m_sate = APPLICATION_RUNNING; return true; }
    bool pause() { m_state = APPLICATION_PAUSED; return true; } 
    // resume may keep track of time if the application uses a timer.
    // This is what makes it different than start() where the timer
    // in start() would be initialized to 0. And the last time before
    // paused was trigger would be saved, and then reset as new starting
    // time for your timer or counter. 
    bool resume() { m_state = APPLICATION_RUNNING; return true; }      
    bool exit(); { m_state = APPLICATION_EXIT;  return false; }

};

int main() {
    Application app;
    app.start();

    // One Type Of Infinite Loop, with a safety net.
    while ( !app.exit() ) {
        // do some work
    }

    // Another Type Similar But Different
    while ( app.getState() == Application::APPLICATION_RUNNING ) {
      // do some work  
    } 

    // A Third Type
    while ( true ) {
       switch( app.getState() ) {
           case Application::APPLICATION_RUNNING {
               app.start(); // If Not Done Above Outside of Loop
               // Do Some Work
               break;
           }
           case Application::APPLICATION_PAUSE {
               // Wait Till You Has Focus Or Continues
               break;
           }
           case Application::APPLICATION_EXIT {
               // Change The Application State
               app.pause();
               break;
           }
           default: {
               // ErrorHandling Throw An Exception Etc.
           }

        } // switch
    } while

    return 0;
}

Some Of These Types of methods you may not necessarily see in the 主编. You would see these types of loops within your application class that are done privately and invoked publicly so that your 主编 would look cleaner as such:

主编

#include "Application.h"

int main() {

    try {
        // Initialize Loggers, Settings, Process - Thread Blockers etc.

        // Handle Input Arguements

        // Give The Main Thread Application, Window Handle, Mutex etc, A Unique Name
        const std::string strApplicationName( "My Application" );
        Application app( strApplicationName );
        app.start();

        }

    } catch( YourTypes& e ) {
        // Print Errors To Either File Or Console
        return RETURN_ERROR; 
    } catch ( ... ) {  // Default Types
        // Print Errors To Either File Or Console 
        return RETURN_ERROR;     
    } 

    return RETURN_OK; // return 0;
}

因此,你的主要工作是干净的,容易跟踪,你在申请类别物体内正在 lo。 这样,只要申请运行,你就能够继续有无限的休息。 现在,如果你是书写司机、档案或记忆监测员、恶意或抗病毒的 d或过程,那么你可能不想这样做,但是,由于这些过程是在窗户背景下进行的,如果这一进程或可执行的进程没有范围和目的,我们仍然希望安全地撤出所有场所,清理所有记忆,这仍然是安全的。

这里的Paradigm是安全而高效地管理结构良好的应用。 我把这个例子当作一个例子,就是当你摆脱由书面活动驱动或数据驱动的各类申请,并从事任何类型的游戏发展时,这是一种适当的模式。 唯一的区别,不是把你的类别命名为“申请”,而是你更可能地称其为“游戏”,并且拥有从“搜索引擎”类别继承的“游戏”。 这样,法典就能够重新用来建立和发展多种游戏。 处理所有图象、声音、字体、投放等,是笼统的,如果这一基类不能自行上调,那么该发动机类别就算是抽象的,那么你就不得不将“猎物”作为可瞬息的继承类别。 您还可能想让发动机舱从单一吨类别继承,这样你就只能有一例游戏:发动机物体。 然后,游戏组将负责装满的所有资产、装饰设计、装饰、装装货、装装货等,这是这一游戏所独有的东西。 这使得它非常具有模块性。 这一设置还将要求发动机建造严重依赖模板的多级管理人员。

This following is not my work, but is a project I ve been working on and all credit goes to Marek A. Krzeminski, MASc at http://www.marekknows.com This excerpt shows the 主编 file.

// Version: 1.0
// Copyright (c) 2012 by Marek A. Krzeminski, MASc
// [email protected]

#include "stdafx.h"
#include "BuildConfig.h"
#include "Settings.h"
#include "BlockProcess.h"
#include "Logger.h"
#include "Utility.h"

#include "Game.h"

// ----------------------------------------------------------------------------
// _tmain()
// Main Entry Point Into Application
int _tmain( int iNumArguments, _TCHAR* pArgumentText[] ) {
    using namespace vmk;

    try {
        // Test If Engine Is Supported By This Compiler
        Utility::testPlatform();

        Logger logger( "logger.txt" );
        Settings settings;

        // Prevent Starting Game Multiple Times At Once
        BlockProcess processBlocker( settings.getNameAndVersion() );
        if ( processBlocker.isBlocked() ) {
            std::ostringstream strStream;
            strStream << settings.getNameAndVersion() << " is already running in another window" << std::endl;
            throw ExceptionHandler( strStream, false );
        }

        // Handle Input Arguments
        bool bShowHelp = false;
        for ( int i = 1; i < iNumArguments; ++i ) {
            std::ostringstream strStream;
            strStream << "Input Argument " << i << ": " << pArgumentText[i];

            std::string strArgument( Utility::toLower( std::string( pArgumentText[i] ) ) );

            if ( strArgument.compare( "/?" ) == 0 || strArgument.compare( "help" ) == 0 ) {
                bShowHelp = true;
            } else if ( strArgument.compare( "window" ) == 0 ) {
                settings.setWindowDisplayMode( true );
            } else if ( strArgument.compare( "debug_memory" ) == 0 ) {
                settings.setDebugLogging( settings.getDebugLogging() | Settings::DEBUG_MEMORY );
            } else if ( strArgument.compare( "seed" ) == 0 ) {
                // Need Next Argument To Know Which Seed Value To Use
                bool bError     = false;
                unsigned uSeedValue = 0;
                if ( i + 1 < iNumArguments ) {
                    uSeedValue = Utility::convertToUnsigned( std::string( pArgumentText[i+1] ) );
                    if ( uSeedValue == 0 ) {
                        bError = true;
                    } else {
                        settings.setRandomNumberSeed( uSeedValue );
                        i++; // Move Argument Counter Past Seed Value
                    }
                } else {
                    bError = true;
                }

                if ( bError ) {
                    // Missing Argument For Seed Value
                    std::cout << " <- Missing Seed Value After This Argument";
                } else {
                    // Display Seed Value To Use
                    strStream << " " << uSeedValue;
                }           
            } else {
                strStream << " <- Unrecognized input argument";
            }

            Logger::log( strStream, Logger::TYPE_CONSOLE );
        }

        if ( bShowHelp ) {
            std::ostringstream strStream;
            strStream << std::endl
                      << settings.getNameAndVersion() << " command line arguments:" << std::endl
                      << "  seed nnn     | Supply seed value (nnn) to use in random number generator" << std::endl
                      << "  window       | Run the program in a window rather then full screen" << std::endl
                      << "  debug_memory | Log extra messages when objects are allocated in memory" << std::endl
                      << std::endl;
            Logger::log( strStream, Logger::TYPE_CONSOLE );

        } else {
            // Run The Game Here
            Game game;
            game.start();

        } 
    } catch( ExceptionHandler& e ) {
        std::cout << "Exception Thrown: " << e.getMessage() << std::endl;
        Utility::pressAnyKeyToQuit();
        return RETURN_ERROR;
    } catch( ... ) {
        std::cout << __FUNCTION__ << " Caught Unknown Exception" << std::endl;
        Utility::pressAnyKeyToQuit();
        return RETURN_ERROR;
    }

    return RETURN_OK;

 } // _tmain

As you can see there is no visible infinite while or for loop visible here since this type of algorithm is nested deep within the Game - Engine object.





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签