False memory leaks with OpenCV e MFC on Visual Studio
False memory leaks on Visual Studio with OpenCV and MFC is a known "false" problem. Even if the solution is easy a lot of people is looking for. This article shows the solution step by step.
The reason of the problem is that check for memory leaks happens after that MFC is unloaded. But because user DLLs are unloaded after MFC the check will found allocated memory and reports memory leaks. For this reason we have false leaks.

Because of "false leaks" we can ignore them. Point is that we can't know which one are false and which are right. It important to remove false leaks so we can be warned if our code is generating any memory leaks.
To remove false leaks we have 2 options:
- Option 1) Use static link for MFC (or OpenCV)
- Option 2) Use Delay Loaded Dlls
Static link for MFC
Using static link for MFC solves the problem because MFC become part of our executable. The memory check happens when the EXE is unloaded than after that DLL are unloaded.
In order to use Static Link for MFC is enough to set the option Project Properties > Configuration Properties > General > Use of MFC >Use MFC in a Static Library.

We want to go in details for consequence of this choice
Use Delay Loaded Dlls
Out project can be set to use Delay Loading Dlls such as OpenCV.
Using this option user DLL are loaded at 1st needs (therefore after MFC). Because the unloading of DLL is reverse as loading, user DLL (and related memory) will be unloaded before MFC. On this way the memory check is fired at right time and memory should be empty.
Configure Delay Loading of OpenCV
In order to use Delay Loaded Dll we have to list all DLLs we are using in:
Project Properties > Configuration Properties > Linker > Input > Delay Loaded Dlls.

In OpenCV each module has a LIB file. Used module have to be listed in the additional dependencies of the linker. The linker will link the module we will really use in our code. Each LIB has a DLL that we have to list in the Delay Loaded option.
Warning 4199
It's common to list all available OpenCV LIB as linker dependencies because the linker will link only the used on. If we list also all available OpenCV DLL as delay loaded option, at link time Visual Studio will show a warning for each UNused DLL:
1>LINK : warning LNK4199: /DELAYLOAD:opencv_features2d320d.dll ignored; no imports found from ... 1>LINK : warning LNK4199: /DELAYLOAD:opencv_...
Use can disable the warning using /ignore:4199 in
Project Properties > Configuration Properties > Linker > Command Line > Additional Options.
Debug o Relase ?
Developer can choose to use delay loaded option for Debug and/or Release configuration. For example we can use delay loaded only in debug configuration but not for Release because we have already checked for memory leak in Debug mode.
This work is property of Pk Lab. You can use it for free but you must retain author's copyright.