I was working on a project involving JNI and I wanted to make my life easier with things like global references to classes and so forth.
During those attempts, I made a class called JavaClass which keeps a permanent global reference to a certain Java class (as the name implies), and I used a static map to access that cache, the class looks more or less like this:
#pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include "jni/jni.h"
namespace Interface
{
class Context;
class JavaClass
{
public:
explicit JavaClass(const std::string& className);
virtual ~JavaClass();
static std::shared_ptr<JavaClass> getInstance(const std::string& className)
{
//
// The line below this one is the one causing the error.
// After some testing, every reference to m_classes causes an access violation.
//
if (m_classes.contains(className))
{
std::cout << "JavaClass returning ref\n";
return m_classes[className];
}
m_classes[className] = std::make_shared<JavaClass>(className);
return m_classes[className];
}
// --[stripped irrelevant parts]--
protected:
JavaClass() = delete;
private:
inline static std::unordered_map<std::string, std::shared_ptr<JavaClass>> m_classes;
// --[stripped irrelevant parts]--
};
}
I've figured that no matter what I do, referencing m_classes inevitably gives off an access violation and the debugger says that there is an attempt to dereference the address of 0x68.
I've confirmed this by just entirely removing the testing mechanism and trying again:
static std::shared_ptr<JavaClass> getInstance(const std::string& className)
{
// This works!
return std::make_shared<JavaClass>(className);
}
This is code running C++23. I really couldn't figure out why this is causing an access violation, I'd appreciate any help here.