Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor and Destructor of initialized static thread_local struct not invoked

Tags:

c++

The code below supposedly initializes a static thread-local and static struct.

#include <iostream>

struct Tracer {
public:
  Tracer(const char *new_name) : name{new_name} {
    printf("%s : Constructor()\n", this->name);
  }

  ~Tracer() {
    printf("%s : Destructor()\n", this->name);
  }

private:
  const char *name;
};

// 1. Thread-Local Storage Duration
static thread_local Tracer t_thread_local{"Thread-Local Storage Duration"};

// 2. Static Storage Duration
static Tracer t_static{"Static Storage Duration"};

int main() {
  printf("Start Program\n");
}

However, I don't see the message expected from the static thread-local struct Constructor/Destructor. The output printed only shows messages from the static struct. Am I missing something?

Static Storage Duration : Constructor()
Start Program
Static Storage Duration : Destructor()
like image 346
cchaos Avatar asked Dec 09 '25 00:12

cchaos


1 Answers

Your assumption that merely declaring & defining these objects must assuredly trigger pre-main construction is incorrect.

[basic.stc.thread/2]: [ Note: A variable with thread storage duration is initialized as specified in [basic.start.static], [basic.start.dynamic], and [stmt.dcl] and, if constructed, is destroyed on thread exit ([basic.start.term]). — end note ]

[basic.start.dynamic/5]: It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized. [..]

There are in fact a number of similar rules in basic.start.dynamic.

Point is, your program doesn't do very much, and it certainly doesn't use t_thread_local, so it's up to the compiler as to whether t_thread_local will ever really exist and, if so, when.

like image 110
Lightness Races in Orbit Avatar answered Dec 10 '25 14:12

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!