c++ - Memory leak in this situation with DirectX COM objects? -


if have class or struct this:

bool localscopefunc()  {     bool result;     idxgifactory* pfactory;     idxgiadapter* padapter;           result = //do here objects  	if (!result) return false;      	result = //do here objects  	if (!result) return false;      	result = //do here objects  	if (!result) return false;    // , on......            //___do cleanup here___//    pfactory->release(); pfactory = nullptr;    padapter->release(); padapter = nullptr;         return true; // if passes  }

if @ point during function fails , returns false, doesn't cleanup @ end, not calling ->release() on objects. mean memory leak?

if so, can't figure out feasible way it, i'll have list of function calls, @ each stage initialising new, , if had clean in reverse this:

int main()  {   if (!inittime())    {return -1;}   if (!initd3d())     {shutdowntime(); return -2;}   if (!initcamera())  {shutdownd3d(); shutdowntime(); return -3;}   if (!initsound())   {shutdowncamera(); shutdownd3d(); shutdowntime(); return -3;}   if (!initphysics()) {shutdownsound(); shutdownd3d(); shutdowntime(); return -4;}  // , on.      return 0;   }

yes, leak because skipping clean-up. com objects use reference-counting, , deal count has accurate system delete memory @ right time.

the solution here easy: use microsoft::wrl::comptr. smart-pointer takes care of calling release if needed no matter how leave scope.

the other thing note com objects don't return errors bools. hresults. should not ignore them, because if function returns hresult can fail. shouldn't use == s_ok or like. should use failed macro, succeeded macro, or dx::throwiffailed.

#include <wrl/client.h>  using microsoft::wrl::comptr;  bool localscopefunc() {     comptr<idxgifactory> pfactory;     comptr<idxgiadapter> padapter;       hresult result = //do here objects     if (failed(result)) return false;      result = //do here objects     if (failed(result)) return false;      result = //do here objects     if (failed(result)) return false;      // , on......      return true; // if passes } 

for more on using comptr, see this.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -