V623. Consider inspecting the '?:' operator. A temporary object is being created and subsequently destroyed.
The analyzer has detected a possible error occurring when handling the ternary operator '?:'. If, while handling the '?:' operator, an object of the class type and any other type which can be cast to this class are used together, temporary objects are created. The temporary objects will be destroyed after exiting the '?:' operator. An error occurs if we save the result into a pointer-variable in this case.
Consider this example:
CString s1(L"1"); wchar_t s2 = L"2"; bool a = false; ... const wchar_t *s = a ? s1 : s2;
The result of executing this code is the 's' variable pointing to the data stored inside a temporary object. The trouble is that this object is already destroyed!
This is the correct code:
wchar_t s1 = L"1"; wchar_t s2 = L"2"; bool a = false; ... const wchar_t *s = a ? s1 : s2;
This is another code variant which is correct too:
CString s1(L"1"); wchar_t s2 = L"2"; bool a = false; ... CString s = a ? s1 : s2;
The V623 warning demands better attention from the programmer. The trouble is that errors of this type can hide very well. A code containing such errors may work successfully for many years. However, it's only an illusion of correct operation. Actually it is the released memory which is being used. The fact that there are correct data in memory is just a matter of luck. The program behavior can change any moment. It can occur as you switch to another compiler version, or after code refactoring, or when a new object appears which uses the same memory area. Let's study this by example.
Let's write, compile and run the following code:
bool b = false; CComBSTR A("ABCD"); wchar_t *ptr = b ? A : L"Test OK"; wcout << ptr << endl;
This code was compiled with Visual Studio 2010 and it printed "Test OK". It seems to be working well. But let's edit the code a bit:
bool b = false; CComBSTR A("ABCD"); wchar_t *ptr = b ? A : L"Test OK"; wchar_t *tmp = b ? A : L"Error!"; wcout << ptr << endl;
It seems that the string where the 'tmp' variable is being initialized won't change anything. But it's not true. The program now prints the text: "Error!".
The point is that the new temporary object was using the same memory area as the previous one. By the way, note that this code can work quite successfully in certain circumstances. Everything depends on luck and phase of Moon. It's impossible to predict where temporary objects will be created, so don't refuse fixing the code proceeding from the idea "this code has been working right for several years, so it has no errors".
This diagnostic is classified as:
You can look at examples of errors detected by the V623 diagnostic.