简体   繁体   中英

Constructor and Destructor of initialized static thread_local struct not invoked

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM