Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++17 inline + thread_local vs thread_local

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?

like image 625
Jes Avatar asked Jul 10 '19 22:07

Jes


1 Answers

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.

like image 148
Baptiste Wicht Avatar answered Oct 09 '22 19:10

Baptiste Wicht