Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initialize function-local static variables using "T& t = *new T" #3157

Open
wants to merge 2 commits into
base: v1.x
Choose a base branch
from

Conversation

lixingcong
Copy link

It would be safer if init the static object with reference according to Google C++ Style Guide.

I compile the static lib, link to my program, then get segmentation fault on calling mdc::get_context(). After applying these patches the bug was gone. 💯

@gabime
Copy link
Owner

gabime commented Aug 17, 2024

Thanks but now tests fails with “LeakSanitizer: detected memory leaks”. A possible solution would be to delete those objects in spdlog::shutdown() and call it at the end of tests.

@lixingcong
Copy link
Author

So hard to free memory of thread_local object created by T& t=*new T

#include <iostream>
#include <thread>

struct A {
	A(int i)
	    : a(i)
	{
		std::cout << "ctor(), i=" << a << std::endl;
	}

	~A()
	{
		std::cout << "dtor(), i=" << a << std::endl;
	}

	const int a;
};

static A& get_a()
{
	static thread_local A& a = *new A(8);
	static thread_local A  b(100);
	return a;
}

int main()
{
	std::thread t([]() { get_a(); });
	t.join();
	return 0;
}

Compile with gcc 11 it got weird print:

ctor(), i=8
ctor(), i=100
dtor(), i=100

That is why LeakSanitizer tell us memory leak happened.

@gabime
Copy link
Owner

gabime commented Aug 19, 2024

This has to solved somehow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants