Is passing a pointer by reference the correct way to do this?

This is my function:

void CreateRenderTarget(HWND, ID2D1HwndRenderTarget*);

and there is how it works:

void D2DRes::CreateRenderTarget(HWND hwnd, ID2D1HwndRenderTarget* pRT)
{
    RECT rc;
    GetClientRect(hwnd,&rc);

    pFactory->CreateHwndRenderTarget(
            D2D1::RenderTargetProperties(),
            D2D1::HwndRenderTargetProperties(
                hwnd,
                D2D1::SizeU(
                    rc.right - rc.left,
                    rc.bottom - rc.top)),
                &pRT);
}

It is called like this:

pD2DRes->CreateRenderTarget(map.GetHWnd(),map.GetpRT());

Once returning from CreateRenderTarget(), map.pRT is NULL. How comes?

Edit: There is my GetpRT() function:

ID2D1HwndRenderTarget* MapEditor::GetpRT()
{
    return pRT;
}

Upvotes: 0

Views: 174

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126432

First problem:

Once returning from CreateRenderTarget(), map.pRT is NULL. How comes?

Because you are not passing the pointer by reference. In order to pass it by reference, the signature of CreateRenderTarget() should be:

void CreateRenderTarget(HWND, ID2D1HwndRenderTarget*&);
//                                                  ^

Unless you do that, your CreateRenderTarget() would be working on a copy of the pointer passed as an argument, and changes to its value won't affect the original pointer.

Second problem:

You write:

[...] There is my GetpRT() function:

ID2D1HwndRenderTarget* MapEditor::GetpRT()
{
    return pRT;
}

Notice, that GetpRT should also return a reference to the internal pRT pointer, otherwise the above change won't have an effect (you would be passing by reference a copy of the original pRT.

Therefore, you should modify its signature accordingly:

ID2D1HwndRenderTarget*& MapEditor::GetpRT()
//                    ^
{
    return pRT;
}

Upvotes: 2

Sharath
Sharath

Reputation: 1775

This is a very strange code. You are passing everything by value, and expect to modify the value in the function.

If you plan to modify the pointer that is passed to the function, the prototype should as follows:

void CreateRenderTarget(HWND, ID2D1HwndRenderTarget*& pRT);

Upvotes: 0

Related Questions