MFC Serialization behavior change between VC6 and VC7

We recently decided to port one of our existing MFC applications from VC6 to Visual Studio 2003 (VC7.1). This particular application uses MFC serialization to persist MFC object graphs to disk. After some minor changes to get the application to compile, things generally looked good. However, some additional testing discovered that the serialization process was resulting in corrupted files. After a little tracing, we found that the problematic code did something like this in one of the object's Serialize method:
 ...
VARIANT varValue;
GetBSTRVariantValue(&varValue);
ar << varValue.bstrVal;

The VC6 version of this code worked fine, but not the VC7 version. Stepping through the code in the debugger revealed the issue - the CArchive operator<< overload for the bool data type was being called, even though we were trying to serialize a BSTR. The result is that only the first byte of the string was being serialized - not good. Since this code hadn't changed for years, it was clearly due to a change in the compiler behavior, not the code behavior.

We went back to the VC6 version of the code and stepped through the code in the debugger. The result? It turns out that when serializing BSTRs in VC6, the CArchive operator<< overload for CString, rather the overload for bool. The VC6 compiler was generating an implicit conversion to CString during serialization. Making that conversion explict in the VC7 version of the code resolved the problem.

In fairness to the VC7 compiler, I believe it was generating a compiler warning for this code, which happened to be lost in some other warnings. Yet another reason to be sure that your code compiles without any warnings.






No Comments