Frage

int listenPort()
{
    //if (server)
    //{
    //    return server->port();
    //}
    //std::cout << server->port() << std::endl;
    //return 0;

    //add below 2 lines only to make it work right under Realease.
    //std::fstream f("Z:/fsfasjlfjal.txt");
    //f.close();

    if (_listenPort != -1)
    {
        return _listenPort;
    }

    return 0;
}

I have one function named listenPort, variable _listenPort has been set to -1 in construct function, I want to check its value. When it changes return it or return 0.

I use Visual Studio 2010 to compile the code, DEBUG everything is OK. But when I change to Release(/O2), function always return 0. I tried add two lines code: fstream open and close. Now it seems everything is right.

But this solution is ugly, I just open and close some file. What should I do? Thanks.

War es hilfreich?

Lösung

One not recommended solution is to make replace int _listenPort; with volatile int _listenPort;. Read this to understand why this solution is not recommended.

A good solution would use synchronized writing and reading of _listenPort.

Or As I suggested before move definitions of class to a different file. This way, compiler won't inline your code and function will return expected value.

Andere Tipps

You're probably trying to run a debugger on an optimised (/O2) code and set breakpoints in your function. This is not going to work. Compiler is free to change order of your code as it sees fit, provided that the outcome of the code is the same as if it were untouched.

If you really want to test some values with optimised code, you need to log the values somewhere (a file) or print them out in the console.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top