Skip to content

static local variables : show the initialization checks #119

@Lectem

Description

@Lectem

When static is used in a function, initialization of the variable will only happen on the first time the block scoped is reached. Since c++11, this is even thread_safe.

I suggest transforming the following code:

struct StructWithCtor
{
    StructWithCtor() { }
};

void func()
{
    static StructWithCtor structWithCtorInstance;
}

to the following for C++11 onward

struct StructWithCtor
{
    StructWithCtor() { }
};

void func()
{
//  static local variable means we need to support thread-safe, one-time initialization . The compiler will generate code like the following:
//
//  if ( obj_guard.first_byte == 0 ) {
//      if ( __cxa_guard_acquire(&obj_guard) ) {
//        try {
//          ... initialize the object structWithCtorInstance ...;
//        } 
//        catch (...) {
//          __cxa_guard_abort(&obj_guard);
//          throw;
//        }
//        ... queue object destructor of structWithCtorInstance with __cxa_atexit() ...;
//        __cxa_guard_release(&obj_guard);
//      }
//   }
//
    static StructWithCtor structWithCtorInstance;
}

Note the comment is adapted from Apple Clang : www.opensource.apple.com/source/libcppabi/libcppabi-14/src/cxa_guard.cxx

I think in this case we can leave it as a comment, because we would otherwise need to add something like
alignas(alignof(StructWithCtor)) char func_structWithCtorInstance _storage[sizeof(StructWithCtor)]; in the global scope and pull in the <new> header for placement new and then have new (&func_structWithCtor_storage) StructWithCtor();.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions