Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use the address of a constexpr variable?

I have a variable whose address is passed as the fourth parameter to setsocketopt. Notice that this parameter is declared as a constant pointer (const void *optval).

In a patch I put up for review I changed the declaration of that variable to static constexpr. A reviewer of this change had concerns: he felt that it was questionable whether you can always take the address of a constexpr. He suggests that I make it const. I couldn't find much about addresses of constexpr variables and concerns about it after googling around. Can someone explain what the guarantees are concerning the address of a constexpr variable and what the caveats are about using it (if any)?

In case it's helpful, here's the code (I added static constexpr, it was just an int before):

static constexpr int ONE = 1;
setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &ONE, sizeof(ONE));

Thanks!

like image 562
firebush Avatar asked Jan 26 '23 06:01

firebush


1 Answers

Every object is guaranteed to have an address per [intro.object]/8

An object has nonzero size if it

  • is not a potentially-overlapping subobject, or

  • is not of class type, or

  • is of a class type with virtual member functions or virtual base classes, or

  • has subobjects of nonzero size or bit-fields of nonzero length.

Otherwise, if the object is a base class subobject of a standard-layout class type with no non-static data members, it has zero size. Otherwise, the circumstances under which the object has zero size are implementation-defined. Unless it is a bit-field, an object with nonzero size shall occupy one or more bytes of storage, including every byte that is occupied in full or in part by any of its subobjects. An object of trivially copyable or standard-layout type ([basic.types]) shall occupy contiguous bytes of storage.

emphasis mine

Since ONE is a non-class-non-bit-field type, it's in storage and you can take its address.

like image 57
NathanOliver Avatar answered Jan 30 '23 14:01

NathanOliver