C++ class Singleton problem

Hi.
I want to implement a simple singleton class in my UE project, but it gives me errors.
Here is my code for header:

class CRYSTALLIZED_API PathfindingManager
{
private:
	PathfindingManager();
	PathfindingManager(PathfindingManager const &);
	PathfindingManager& operator=(PathfindingManager const&);

protected:
	static PathfindingManager *instance;

public:
	static PathfindingManager *GetInstance();
	static void Destroy();
};

Here is my cpp code:

PathfindingManager *PathfindingManager::GetInstance()
{
	if (!instance)
	{
		instance = new PathfindingManager();
	}
	return instance;
}

void PathfindingManager::Destroy()
{
	delete instance;
}

And these are my errors:

  • Error PathfindingManager.cpp.obj : error LNK2019: unresolved external symbol “private: __cdecl PathfindingManager::PathfindingManager(void)” (??0PathfindingManager@@AEAA@XZ) referenced in function “public: static class PathfindingManager * __cdecl PathfindingManager::GetInstance(void)” (?GetInstance@PathfindingManager@@SAPEAV1@XZ)
  • Error PathfindingManager.cpp.obj : error LNK2001: unresolved external symbol “protected: static class PathfindingManager * PathfindingManager::instance” (?instance@PathfindingManager@@1PEAV1@EA)
  • Error D:_WPI\Term2\Mark\UE4\Crystallized\Binaries\Win64\UE4Editor-Crystallized-2148.dll : fatal error LNK1120: 2 unresolved externals

The problem is in accessing instance. When I remove code from cpp functions everything compiles:

PathfindingManager *PathfindingManager::GetInstance()
{
	return NULL;
}

void PathfindingManager::Destroy()
{
}

Please, help me.

Look like you are missing implementations for your constructors and the static instance pointer.

In your cpp add:

PathfindingManager* PathfindingManager::instance;

PathfindingManager::PathfindingManager()
{

}

You only get compile errors when you add the extra code because the compiler is clever enough to ignore it until needed.

I’d delete the other functions unless you need them (watch out for copying by value though).

 PathfindingManager(PathfindingManager const &);
 PathfindingManager& operator=(PathfindingManager const&);

Also - warning - statics don’t get reintialized between launches from the editor (in my experience, mileage may vary).

You’ll probably want a static init function (better in the long run than the on the fly lazy init you have), and to delete your static instance when your app closes down.

Did that work?

Yes, this works. Thanks a lot =)

how did you do the init function and where did you call it?