W2A、OLE2A等 ATL 宏会引发 stack overflow。使用时注意。
最近一个转换文件的程序,在转换大批量文件是老是 stack overflow。
查来查去。。原来是 在大循环中用了W2A和A2W两个宏。
MSDN的 TN059: Using MFC MBCS/Unicode Conversion Macros 有描述,这两个宏在大循环中要有特殊的写法,不然保不准就 stack overflow。
Other Considerations
Do not use the macros in a tight loop. For example, you do not want to write the following kind of code:
void BadIterateCode(LPCTSTR lpsz) |
The code above could result in allocating megabytes of memory on the stack depending on what the contents of the string lpsz is! It also takes time to convert the string for each iteration of the loop. Instead, move such constant conversions out of the loop:
void MuchBetterIterateCode(LPCTSTR lpsz) |
If the string is not constant, then encapsulate the method call into a function. This will allow the conversion buffer to be freed each time. For example:
void CallSomeMethod(int ii, LPCTSTR lpsz) |
Never return the result of one of the macros, unless the return value implies making a copy of the data before the return. For example, this code is bad:
LPTSTR BadConvert(ISomeInterface* pI) |
The code above could be fixed by changing the return value to something that copies the value:
CString BetterConvert(ISomeInterface* pI) |
The macros are easy to use and easy to insert into your code, but as you can tell from the caveats above, you need to be careful when using them.