Reputation: 4001
I'm using Wt::WFormModel, the examples for which represent field names as static const char*
's. I made a bunch of changes to my project at one time, one of which was changing the field representation to be constexpr
. After much troubleshooting, I found this statement in the WFormModel documentation:
The Field type is
const char *
, and instead of string comparisons to identify fields, pointer comparisons are used. Thus you really should use the same field constant throughout your code to refer to a given field, and you cannot use C++11constexpr
for the field constant since that does not have a unique value (since it has no storage).
How does the representation of a constexpr char*
compare to the representation of a const char*
?
Upvotes: 0
Views: 67
Reputation: 473627
It's for the same reason that this doesn't necessarily work:
const char *lit1 = "foo";
const char *lit2 = "foo";
assert(lit1 == lit2);
The compiler could recognize that these two literals are in fact the same value, and in so doing give them the same storage. But it might not. And the standard doesn't require it to.
And if lit1
and lit2
are in different files, then giving them the same pointer value goes from being a compiler trick to a linker trick. That's much less likely to happen.
One way to think of constexpr
is as a complex way of creating literals. As such, a constexpr
variable is like a literal; its storage, if it has any, is not bound to any one translation unit or point of usage. The compiler/linker could collate them all together... or it could not. The standard doesn't require them to.
Upvotes: 2