Jimmyt1988
Jimmyt1988

Reputation: 21126

Passing HWND through to a method and storing in a class

I am calling the following:

// hMainWindow is a correctly functioning window handle
app.GetMainWindowInfo().SetHndToWindow( hMainWindow );

Here are my classes:

class App : public BaseClass
{
public:

    WindowInfo& GetMainWindowInfo();
    void SetMainWindowInfo( unique_ptr<WindowInfo> windowInfo );

private:

    WindowInfo mainWindowInfo;

};

class WindowInfo
{
public:

    HWND& GetHndToWindow() const;
    //void SetHndToWindow( HWND hndToWindow );

            // implementation on cpp file included here simply for example

            void WindowInfo::SetHndToWindow( HWND hndToWindow )
            {
                this->hndToWindow = hndToWindow;
            }

private:

    HWND hndToWindow; // Only for Windows OS

};

Now when i try and use the Getter method GetHndToWindow, I'm getting an unused back with unable to read memory.

Any ideas where i might be going wrong?

enter image description here

Moving on from the above issue, in for example the app class, if i check the debugger at this line:

enter image description here

My graphicContext class looks like this:

class IGraphicContext
{
    // Methods
public:

    virtual void Initialize() = 0;

private:

    // Properties

public:

    const WindowInfo& GetWindowInfo() const
    {
        return this->windowInfo;
    }

    void SetWindowInfo( WindowInfo& windowInfo )
    {
        this->windowInfo = windowInfo;
    }

protected:

    WindowInfo windowInfo;

};

class DXGraphicContext : public IGraphicContext, public BaseClass
{
    // Methods
public:

    DXGraphicContext();
    ~DXGraphicContext();

    virtual void Initialize() override;
   ...

Upvotes: 1

Views: 1134

Answers (1)

Jonathan Potter
Jonathan Potter

Reputation: 37132

Your IGraphicContext::SetWindowInfo method makes a copy of the passed in WindowInfo. If the original is then modified later on (e.g. by calling SetHndToWindow) this won't affect the copy that IGraphicContext holds.

If you really want to share a structure like this between two separate classes you should look at holding it in a std::shared_ptr.

Upvotes: 2

Related Questions