Naveen Gara
Naveen Gara

Reputation: 375

constexpr const char* in header file

Is there a reason to not use "constexpr const char*" in header file?

The argument from a colleague is that every translation unit including this header file would have a copy.

My understanding was that since its compile-time constant, no memory is allocated and acts more like a "#define" macro with respect to memory usage. Here is the source,

TestConstExpr.h

  #include <string.h>
  namespace TestConstExpr
  {
    constexpr const char* TIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
    constexpr const int TIME_FORMAT_SIZE = strlen(TIME_FORMAT) + 1;

    class TestClass
    {
        char arr[TIME_FORMAT_SIZE];
    }
  }

Upvotes: 2

Views: 3826

Answers (1)

eerorika
eerorika

Reputation: 238281

The argument from a colleague is that every translation unit including this header file would have a copy.

You're colleague is technically correct. But it doesn't matter, since the redundant copies are thrown away when the units are linked together.

Although, I've seen comments about this not being necessarily the case on some non-standard-conforming systems when dynamic linking is involved.


constexpr const char* TIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
.... sizeof(TIME_FORMAT)

This doesn't do what you probably think it does. It gives you the size of the pointer, not the size of the pointed string.

constexpr const int TIME_FORMAT_SIZE = strlen(TIME_FORMAT) + 1;

Your attempted fix also doesn't work, because strlen is not a constant expression.

You can fix the problems by using a reference to the string literal:

static constexpr auto& TIME_FORMAT = "yyyy-MM-dd hh:mm:ss";
constexpr const int TIME_FORMAT_SIZE = sizeof(TIME_FORMAT);

Upvotes: 4

Related Questions