vendredi 15 juillet 2022

constructing completely private and anonymous static singleton

I was trying to think of a way how to deal with C libraries that expect you to globally initialize them and I came up with this:

namespace {

class curl_guard {
public:
    curl_guard()
    {
        puts("curl_guard constructor");
        // TODO: curl_global_init
    }
    ~curl_guard()
    {
        puts("curl_guard destructor");
        // TODO: curl_global_cleanup
    }
};

curl_guard curl{}; // nothing is ever printed to terminal

}

But when I link this into an executable and run it, there's no output, because it is optimized out (verified with objdump), even in debug build. As I understand, this is intended, because this type is never accessed in any way. Is there any way to mark it so that it is not excluded? Preferably without making it accessible to the user of the library. I'd prefer a general solution, but GCC-only also works for my purposes.

I am aware of typical singleton patterns, but I think this is a special case where none of them apply, because I never want to access this even from internals, just simply have a class tucked away which has one simple job of initializing and deinitializing a C library which is caused by the library being linked in and not something arbitrary like "just don't forget to construct this in main" which is as useful as going back to writing C code.

Aucun commentaire:

Enregistrer un commentaire