0
votes

I am new to MFC.

How to release resource which is passed as (WPARAM) in SendMessage().

Here I using "new" to create for it. Following is the snapshot for same.

void Build::BuildCube()
{

    SCtPt *data = new SCtPt;
    data->vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM) dir);
}

I want to make sure "data" resource get released of this function.

Thanks...

3
What is MFrame, and how does it handle that message? Does it keep a reference to that pointer around somewhere? Assuming not, you can safely delete once it's finished handling that message, which will be after SendMessage returns.The Forest And The Trees
Additionally if not, it may be easier for you to either create an automatic variable or use shared_ptr.The Forest And The Trees

3 Answers

5
votes

Did you consider writing the code like this:

void Build::BuildCube()
{
  SCtPt data;
  data.vm = true;
  int dir = 100;
  MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)&data, (LPARAM)dir);
}

That way the data sent as WPARAM is still a pointer to your object, but when the application gets out of this method's scope, it will invoke the destructor and perform the cleanup for you.

3
votes

As the SendMessage() API is a synchronous API, it sends the message to the other window procedure before returning. When the call to SendMessage() returns, then data can be freed/released:

void Build::BuildCube()
{
    SCtPt *data = new SCtPt;
    data->vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM)dir);
    delete data;
}

Or, better yet, you can avoid allocating the data on the heap altogether. Simply allocate it on the stack and let RAII handle the rest:

void Build::BuildCube()
{
    SCtPt data;       // don't use "new", so you won't get a pointer
    data.vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM)dir);
    // no delete necessary!
}
0
votes

We usually do this :

At the point the data is allocated, the comment state explicitly where it will be deallocated.

void Build::BuildCube()
{

    SCtPt *data = new SCtPt; // Will be deallocated in handler of message WM_MAP_NEW
    data->vm = true;
    int dir = 100;
    MFrame()->SendMessage(WM_MAP_NEW, (WPARAM)data, (LPARAM) dir);
}

LRESULT CMainFrame::OnMapNew(WPARAM wParam, LPARAM )
{
  SCtPt *data = (SCtPt*) wParam;
  // do something with data;

  delete data;
}