C++ Singleton Crash when TArray add a object

call ULDataMgr::GetInstance()->NewUObject(); in GameMode Constructor ,the editor crash

code
.h
class ULDataMgr : public UObject
{
GENERATED_BODY()

private:
	ULDataMgr();

	static ULDataMgr* m_Instance;
	TArray<ULMonsterData*> m_MonsterDatas;
	
public:
	
	static ULDataMgr* GetInstance();

	void NewUObject();
};

cpp

ULDataMgr* ULDataMgr::m_Instance;

ULDataMgr* ULDataMgr::GetInstance()
{
	if (!m_Instance)
	{
		m_Instance = NewObject<ULDataMgr>();
	}
	return m_Instance;
}

ULDataMgr::ULDataMgr() 
{
	m_MonsterDatas.Empty();
}

void ULDataMgr::NewUObject()
{
	for (int i = 0; i < 10;i++)
	{
		ULMonsterData* data = NewObject<ULMonsterData>();
		data->AddToRoot();
		data->m_Id = i;
		m_MonsterDatas.Add(data);
		UE_LOG(LogTemp, Log, TEXT("data->m_Id:%d"), data->m_Id);
	}
	
}

crash info:

UE4Editor_MyTest_9469!TArray::ResizeGrow() [d:\epic games\4.12\engine\source\runtime\core\public\containers\array.h:2355]
UE4Editor_MyTest_9469!ULDataMgr::NewUObject() [d:\unrealworkspace\mytest\source\mytest\ldatamgr.cpp:29]

the line 29 :m_MonsterDatas.Add(data);

please help ,thank you.

The only thing I can see off the bat is you aren’t initializing your m_Instance to nullptr/NULL so if you aren’t running in debug that value could be anything and your !m_Instance code in GetInstance may not get called.

Can you post the full callstack including the error?

You strike me like you come from Java :). In Java, Singletons are created in this fashion (though with a synchronized block). CreateInstance is not thread-safe. Its implementation should be:

ULDataMgr* ULDataMgr::GetInstance()
{
    static ULDataMgr* Instance = NewObject<ULDataMgr>();
    return m_Instance;
}

The C++ standard then gurantees thread-safety. This is not the source of error but I wanted to point that out.

Could you please provide the full stack trace? That will make debugging a little easier. The error must occur in AllocatorInstance.CalculateSlackGrow(ArrayNum, ArrayMax, sizeof(ElementType)); at line 2335 in Array.h .

Cheers,
Univise