Home > database >  static shared_ptr not keeping value across function calls
static shared_ptr not keeping value across function calls

Time:07-09

I have an input.hpp (which I won't post for the sake of brevity) and an input.cpp file that looks like this (some things removed):

#include "details/macros.hpp"
#if defined(PLATFORM_WINDOWS)
    #include "details/win32/input.inl"
#else
    #error "No input implementation for this platform."
#endif

#define CHECK_INPUT_TYPE(type)      \
if (types[input_type_bits::type])   \
{                                   \
    auto res = poll_##type();       \
    if (res.code() != errors::ok)   \
        LOG(error) << res;          \
}                                   

namespace input
{
        void poll_input(flagset<input_type_bits> types)
        {
            CHECK_INPUT_TYPE(keyboard)
            CHECK_INPUT_TYPE(mouse)
            CHECK_INPUT_TYPE(touch)
            CHECK_INPUT_TYPE(gesture)
            CHECK_INPUT_TYPE(gamepad)
        }
}

And an input.inl that looks like this (also cut down for brevity):

#ifndef WIN32_INPUT
#define WIN32_INPUT

#include <Windows.h>

namespace input
{
        static bool g_init = false;
        static std::shared_ptr<system::surface> g_surface = nullptr;

        static error<errors> poll_gamepad()
        {
            if (!g_init)
            {
                auto ptr = create_surface();
                g_surface = std::move(ptr);
                g_init = true;
            }

            HWND hwnd = reinterpret_cast<HWND>(g_surface->native_ptr());

            return MAKE_ERROR(errors::ok);
        }
}

#endif

However what is currently happening is that when I try to access g_surface's method, it works for the first call (in which g_init was false) but in the second time the poll_input function is called, according to Visual Studio's debugger, g_surface is empty and accessing the method throws an exception.
What gives? g_init was set to true successfully across calls and yet g_surface wasnt? If I move g_surface to be a static variable inside poll_gamepad it does work properly but that is something I'd like to avoid. Is there something about a static shared_ptr that I'm missing?

CodePudding user response:

I found out the answer to this problem. I mistakingly (don't code while tired people!) had a call to the Win32 API GetKeyboardState that was using the wrong static variable as the output buffer and caused static memory corruption.

Thank you for everyone's help and I apologize for not giving much information to deal with. That was my bad!

Anyways, I'm glad it's working properly now, case closed.

  • Related