Zhang
Zhang

Reputation: 3356

In Visual Studio, How to prevent my useful function being optimized by the compiler?

I did a template string operation class which can operate std::string and MFC CString. It workes fine on the Debug version. It does work on the Release version. By my investigation, I found that at least one useful function is optimized. checkChars is optimized which is supposed to be called in the split. (checkChars isn't being called.)

static bool checkChars(const TCHARTYPE& c, const TCHARTYPE* chrs)
        {
            for ( ;*chrs ;chrs++)
            {
                if (c == *chrs)
                {
                    return true;
                }
            }
            return false;
        }
void split(const TSTRING& s, vector<TSTRING>& v, const TCHARTYPE* separator, bool bKeepEmptyParts = false)
{
...
//here at() is called, but checkChars isn't
if (checkChars(at(s, i), separator))
...
}

The VS Optimization is

Maximize Speed (/O2)

. I found use

Custom

can prevent the Optimization of my useful function. But I want to know why, and I don't want to change the project settings, Can I just modify my code to make it work?

Edit:

After a long time, I realized that the real problem is not Optimization, is that "at()" fuction doesn't return the expected char reference. TSTRING here is CString MFC which does not return a TCHAR reference. The compiler found this would not work, so "optimized" it.

Upvotes: 2

Views: 1590

Answers (1)

Related Questions