gabime / spdlog

Fast C++ logging library.
Other
24k stars 4.5k forks source link

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

Open lixingcong opened 1 month ago

lixingcong commented 1 month ago

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. :100:

gabime commented 1 month ago

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 commented 1 month ago

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 commented 1 month ago

This has to solved somehow