Differences

This shows you the differences between two versions of the page.

Link to this comparison view

cast [2016/09/12 11:04]
rzr
cast [2016/10/26 13:35] (current)
rzr
Line 1: Line 1:
 +==== 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
 +
 +
 +   * http://stackoverflow.com/questions/39441338/what-is-the-proper-way-to-initialize-a-pointer-member-in-c-11
 +   * http://stackoverflow.com/questions/23401489/reinterpret-cast-and-portabilty#
 +
 +</code>
 ==== C cast ==== ==== C cast ====
  
cast.txt ยท Last modified: 2016/10/26 13:35 by rzr
 
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