Jump to content
  • Advertisement
Sign in to follow this  
belfegor

C++ Strange behaviour

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement

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

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!