How do non-integer constants work in C ++?

So, I know that in C ++ constants, by default, a different relationship is used than variables. Therefore I should not set

int foo; 

in some heading - the linker will rightly complain about several definitions . OTOH, I can write

 const int bar = 42; 

in the header, and the compiler ensures that there is only one definition of bar .

It is easy to understand with integral constants how the compiler deals with this - at least until no one takes the address of bar or does some other fun thing that requires an assignment for storage). However, what if someone does this? And what if it's not an integral, but something that is needed to execute the code at runtime? Suppose I put this in the header:

 const std::string baz = "h2g2"; 

Assuming a slight string optimization, this requires dynamic memory allocation at runtime, so the code must be executed, the address must be stored somewhere, etc.

I assume that in the end I get one definition of baz per translation unit, only the compiler assigns it an internal binding to prevent the linker complaining? Or am I missing something?

Note. I'm not interested in constexpr , just in plain old C ++ constants, since they existed from the 80s and were codified in C ++ 98. (However, if a comprehensive answer would include how it all fits with constexpr , I would not complain about it.)

+8
c ++ constants c ++ 98 linkage
source share
1 answer

Declaring an object (in the namespace area) as const in C ++ by default assigns it an internal binding.

If you declare (and define due to initialization)

 const std::string baz = "h2g2"; 

in the header, you will have a statically linked string for each translation unit. The address must be stored in each translation block (different addresses to different char literals not saved by the heap - read-only)

Edit: const constexpr as const ++ as a C ++ 11 constexpr , since it means β€œsuitable for evaluating constant expressions,” so it must have an internal relationship. [Nb. I do not mention C ++ 14]

+4
source share

All Articles