Monday, November 13, 2017

C++17: std::launder

C++17 added the template function std::launder() to handle a corner case with placement new. Here is an example:

#include <iostream>
#include <new>

struct MyStruct
{
  const int mMyConst   ;
        int mMyVariable;
  MyStruct(int myConst, int myVariable)
  : mMyConst(myConst), mMyVariable(myVariable)
  {}
};

int main()
{
  MyStruct * pMyStruct = new MyStruct(1, 2);
  std::cout << pMyStruct->mMyConst    << " "; // Should be okay.
  std::cout << pMyStruct->mMyVariable << " "; // Should be okay.

  MyStruct * pMyStruct2 = new (pMyStruct) MyStruct(3, 4);//Using Placement New.
  std::cout << pMyStruct2->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct2->mMyVariable << " "; // Should be undefined.

  std::cout << pMyStruct->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct->mMyVariable << " "; // Should be undefined.

  new (pMyStruct) MyStruct(5, 6);
  std::cout << pMyStruct->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct->mMyVariable << " "; // Should be undefined.

  std::cout << pMyStruct2->mMyConst    << " "; // Should be undefined.
  std::cout << pMyStruct2->mMyVariable << " "; // Should be undefined.

  //std::cout << std::launder(pMyStruct)->mMyConst    << " ";//Should be okay.
  //std::cout << std::launder(pMyStruct)->mMyVariable << " ";//Should be okay.

  std::cout << std::endl;
  return 0;
}
References:
http://en.cppreference.com/w/cpp/utility/launder
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0532r0.pdf

No comments:

Post a Comment