c++17 inline + thread_local vs thread_local
Asked Answered
I

1

8

I am wondering what exactly the difference between the following two declarations is if both are written in a single header file:

inline thread_local MyClass obj1;  // inline with thread_local
thread_local MyClass obj2;         // no inline

As specified in C++17, adding inline to a variable forces all translation units to see the same address of that variable. Does this mean it's possible for obj2 to get different address values in different translation units? What would be the situation to highlight we should use obj1 rather than obj2?

Isosteric answered 10/7, 2019 at 22:54 Comment(0)
G
4

If you include this header file in multiple compilation units, you will get multiple definitions of obj2. But obj1 will work fine because the linker will guarantee only one definition will exist and all compilation units will use the same definition (and hence the same address).

So, your code should use extern for obj2 and define it in a single compilation unit. But inline already does that for you for obj1.

Does this mean it's possible for obj2 to get different address values in different translation units?

In that particular case, no, since it won't compile. But if you add static to obj2, you will get one address per compilation unit.

What would be the situation to highlight we should use obj1 rather than obj2?

You should never use obj2 like this, obj1 is the correct way. If you want to avoid inline, you could use extern for obj2.

Grownup answered 1/12, 2020 at 7:25 Comment(2)
One notable caveat to this is how DLLs are initialized with their own distinct instance of global variables, including thread-local variables: https://mcmap.net/q/134805/-what-happens-to-global-and-static-variables-in-a-shared-library-when-it-is-dynamically-linkedCracker
If thread_local is the only storage class specifier applied to a block scope variable, static is also implied en.cppreference.com/w/cpp/language/storage_durationLyricism

© 2022 - 2024 — McMap. All rights reserved.