reinterpret_cast

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 ?

Source:

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 :

  http://melpon.org/wandbox/permlink/IlXTqNiVoJtnFDg0
  http://cpp.sh/96mau
  http://coliru.stacked-crooked.com/a/e031835a72ed2172

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

  http://eel.is/c++draft/expr.const#2
  http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf (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

</code>

C cast

/// @author: http://rzr.online.fr/contact.htm
#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)
#else
  struct foo_m {} *m; // this way the type is named and can be used
#endif
};
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>*'
#else
  o.m =
    (struct foo::foo_m*)  //mandatory in c++
    malloc(sizeof( o.m ));
#endif
  return 0;
}
//#eof "$Id: rzr --  --  $"

reinterpret_cast

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