Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior with constexpr static member variable

Tags:

People also ask

Does constexpr need to be static?

A static constexpr variable has to be set at compilation, because its lifetime is the the whole program. Without the static keyword, the compiler isn't bound to set the value at compilation, and could decide to set it later. So, what does constexpr mean?

Does constexpr take memory?

The alternatives don't have the all of the positives of static constexpr - you're guaranteed compile time processing, type safety, and (potentially) lower usage of memory (constexpr variables don't need to take up memory, they are effectively hard coded unless if possible).


This is a follow up question to Undefined reference to static constexpr char[][].

The following program builds and runs fine.

#include <iostream>

struct A {
   constexpr static char dict[] = "test";

   void print() {
      std::cout << A::dict[0] << std::endl;
   }
};

int main() {
   A a;
   a.print();
   return 0;
}

However, if I change A::print() to:

   void print() {
      std::cout << A::dict << std::endl;
   }

I get the following linker error in g++ 4.8.2.

/tmp/cczmF84A.o: In function `A::print()':
socc.cc:(.text._ZN1A5printEv[_ZN1A5printEv]+0xd): undefined reference to `A::dict'
collect2: error: ld returned 1 exit status

The linker error can be resolved by adding a line:

constexpr char A::dict[];

outside the class definition.

However, it's not clear to me why using one of the members of the array does not cause a linker error while using the array causes a linker error.