What is the proper way to initialize a pointer member in C++ (11)?

Any hint to do proper const static member pointer initialization using C++ 11 and later ?


struct App {

static const App* ok;
static constexpr App* ko = reinterpret_cast<App*>(0xBADC0DE); // <= FTBFS

}; const App* App::ok = reinterpret_cast<App*>(0xBADC0DE);

Try it on latest gcc or clang it will fail :

The reason of fail is clear : reinterpret_cast and constexpr are exclusives according to C++11 standard (but was accepted in some compiler). (p125)

But older 2 steps method still works but not single one (on gcc-6.2.0 at least).

This code looks a bit odd, I agree on that but how to get it working or clang or latest g++.

Declaration and init in 2 places can be a workaround but it does not fully explain (init to nullptr is working of course).

Related errors are :

error: 'constexpr' needed for in-class initialization of static data member
error: reinterpret_cast from integer to pointer

More resources:

  reinterpret_cast<> and portabilty


C cast

/// @author:
#include <cstdlib>
// #define FIX // uncomment
/// show why anonymous types are evil in C++
struct foo {
#ifndef FIX
  struct  {} *m; // anonymous type make cast impossible in C++ (ok on C)
  struct foo_m {} *m; // this way the type is named and can be used
int main(int /* argc*/ , char* /* argv*/ [])
  struct foo o; o.m = 0;
#ifndef FIX
  o.m = malloc(sizeof( o.m ));  //error:
  //  invalid conversion from 'void*' to 'foo::<anonymous struct>*'
  o.m =
    (struct foo::foo_m*)  //mandatory in c++
    malloc(sizeof( o.m ));
  return 0;
//#eof "$Id: rzr --  --  $"


cast.txt · Last modified: 2020/09/08 20:41 (external edit)
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki