I found here that according to the C++ standard:
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization.
The C style of coding in my workplace (and by that I mean that other than the file extension, everything is practically C - no exceptions, no templates, no actual classes) obeys the rules specified here, namely exiting from a function in only one place, performing transfer of ownership only when reaching the full-success flow, performing cleanup on locals whose ownership we haven't transferred, etc. Here's a small example (error-code enumeration and other things omitted for brevity):
int func()
{
int iStatus = -1;
PVOID pvSomeData = NULL;
HANDLE hFile = INVALID_HANDLE_VALUE;
pvSomeData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, BUFFER_SIZE);
if (nullptr == pvSomeData)
{
iStatus = 1;
goto lblCleanup;
}
const PTSTR pszFilePath = _T("C:\\temp\\bla.txt");
_tprintf(_T("Writing some stuff into '%s'"), pszFilePath);
hFile = CreateFile(pszFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
iStatus = 2;
goto lblCleanup;
}
// do more stuff, fill pvSomeData, write it to the file, transfer ownership, etc.
// success
iStatus = 0;
lblCleanup:
if (INVALID_HANDLE_VALUE != hFile)
{
CloseHandle(hFile);
}
if (nullptr != pvSomeData)
{
HeapFree(GetProcessHeap(), 0, pvSomeData);
}
return iStatus;
}
This C-style code compiles well under MSVC++, but when attempting to compile it under MinGW-W64, the compiler bemoans the issue of the goto
statement crossing the initialization of pszFilePath
.
From the first link I can see that this would be well formed if I separated the initialization into a declaration and an assignment, since PWSTR
is a POD type.
I'd like to compile my project under MinGW-W64 without performing extensive modifications to my codebase. Is there a way for me to do so (compiler flag, hopefully)?
I'm well aware of the idiomatic way to code this in C++ with RAII classes, but the codebase is flat C-style linear code. I'm also well aware of the strong aversion goto
evokes in developers, and of the fact that any piece of code with a goto
can be written without one. I ask not for style guidance, but for a least-effort way to solve this very specific problem.