Return auto_ptr from dialog proc??


I need to return a heap allocated pointer from a dialog proc, and I was wondering if there was a way to store it in an auto_ptr for exception safety

DialogBoxParam returns an INT_PTR, so i could just call:

T* ptr
EndDialog(handle, reinterpret_cast<INT_PTR>(ptr) );

and recast the return value to T

however, it'd be better to return an auto_ptr<T>, so if something bad happens ptr still gets deleted. sizeof(auto_ptr<T>) returns 4 bytes, so theoretically i should be able to cast it to INT_PTR, but that doesn't seem to work, and it can't be the correct solution anyway.

thanks for the help,
riderrocker
Could you just write a wrapper class that has as a data member the auto_ptr
and implements operator INT_PTR?


I wasn't aware there was an operator INT_PTR...

and if I write a wrapper class A with auto_ptr<T> as a data .member, i'll have to create an A object on the heap in order to return a pointer, which defeats the whole purpose anyway.

maybe i'll just have to return the raw pointer and put it in an auto_ptr right away, but I was hoping for a safer method...

Why would you need to create it on the heap?
Well, I can't return a pointer to a stack object can I?
Does the dialog proc have to return a pointer? Could it just return an instance
of a class that contains the auto_ptr?
well, the prototype for DialogBox and DialogBoxParam is:

INT_PTR DialogBox(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)

so i assume you have to return an int or a pointer, which is 4/8 bytes depending on win32/win64

it'd be nice to return something else though, but i dont know if thats possible
Can you just wrap the function?

1
2
3
4
5
6
7
8
9
10
class MyThingie {
    INT_PTR ptr;
  public:
    explicit MyThingie( INT_PTR p ) : ptr( p ) {}
    ~MyThingie() { /* free it */ }
};

MyThingie MyDialogBox( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam ) {
    return MyThingie( DialogBox( hwnd, message, wParam, lParam ) );
}

yeah, i guess thats what i'll do. I'll replace MyThingie with std::auto_ptr and just use:


auto_ptr<T> auto1( reinterpret_cast<T*>( DialogBox(hwnd, message, wparam, lparam ) );

if that makes sense

sad that i can't return a direct auto_ptr<T> so if DialogBox never returns due to a thrown exception the memory will still get freed

thanks for your help :D
Topic archived. No new replies allowed.