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
?
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 thanobj2
?
You should never use obj2
like this, obj1
is the correct way. If you want to avoid inline
, you could use extern
for obj2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With