What will GetLastError() return after a failed InitOnceExecuteOnce?


The documentation for Init­Once­Execute­Once says

If the function fails, the return value is zero. To get extended error information, call Get­Last­Error.

On the other hand, the documentation for the Init­Once­Callback says

If the function returns FALSE, the block is not marked as initialized and the call to Init­Once­Execute­Once fails. To communicate additional error information, call Set­Last­Error. before returning FALSE.

The second paragraph implies that the Init­Once­Execute­Once function does not itself call Get­Last­Error, because if it did, then that would wipe out the value set by the callback. Is that really the case?

Yes, that's really the case. The remark in the first paragraph about calling Get­Last­Error presupposes that your callback uses Get­Last­Error to report why it wasn't able to initialize.

I agree, however, that the documentation is misleading here.

But if your callback wants to return status information more complex than a single "success/failed", you are probably better served by the synchronous two-phase initialization pattern, which makes it a lot easier to return more complex information. You can even use it to throw a C++ exception.

Comments (4)
  1. > presupposes that your callback uses Get­Last­Error to report why it wasn’t able to initialize

    1. typo: should say SetLastError

      1. Scarlet Manuka says:

        And the same typo, I think, in “… does not itself call GetLastError… “.

  2. Ben Voigt (Visual Studio and Development Technologies MVP with C++ focus) says:

    “The second paragraph implies that the Init­Once­Execute­Once function does not itself call Get­Last­Error”

    I disagree. It can’t call SetLastError after calling the callback, but it can do so before or in lieu of calling the callback.

    For example, if it determines that the callback pointer is invalid (NULL or misaligned) and does not call that callback, then there is no last-error information from the callback to avoid overwriting.

Comments are closed.

Skip to main content