🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Strange behaviour

Started by
2 comments, last by ChaosEngine 5 years, 3 months ago

I had some code that worked before and it doesn't now. I have created minimal c++ project that can reproduce problem.


#include <iostream>

void PrintFooM();

class Foo
{
	int m;

	explicit Foo(int dummy) {}
	Foo();
public:
	static Foo& GetInstance()
	{
		static Foo f;
		return f;
	}

	int GetM() const { return m; }
};

Foo::Foo()
	: Foo(-1)
{
	m = 3;
	PrintFooM();
}

void PrintFooM()
{
	std::cout << "M = " << Foo::GetInstance().GetM() << std::endl;
}

int main()
{
	Foo::GetInstance();
	return 0;
}

Code runs till PrintFooM function is called and its stuck there (like in some endless loop). Never prints anything in console.

I am using VS2017 community.

Advertisement

You have recursive calling in costructor when you invoke Foo::GetInstance constrcuting Foo again


static Foo& GetInstance()
	{
		static Foo f;
		return f;
	}

Debugging this code would have shown this problem almost immediately. Learn to love your debugger.

if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

This topic is closed to new replies.

Advertisement