constexpr array in header

  • A+

I have the following code in a header file, that is included in 2 different cpp files:

constexpr int array[] = { 11, 12, 13, 14, 15 }; inline const int* find(int id) {     auto it = std::find(std::begin(array), std::end(array), id);     return it != std::end(array) ? &*it : nullptr; } 

I then call find(13) in each of the cpp files. Will both pointers returned by find() point to the same address in memory?

The reason I ask is because I have similar code in my project and sometimes it works and sometimes it doesn't. I assumed both pointers would point to the same location, but I don't really have a basis for that assumption :)


In C++11 and C++14:

In your example array has internal linkage (see []/3.2), which means it will have different addresses in different translation units.

And so it's an ODR violation to include and call find in different translation units (since its definition is different).

A simple solution is to declare it extern.

In C++17:

[]/3.2 has changed such that constexpr can be inline in which case there will be no effect on the linkage anymore.

Which means that if you declare array inline it'll have external linkage and will have the same address across translation units. Of course like with any inline, it must have identical definition in all translation units.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: