Using placement new for a polymorphic unique_ptr

Viewed 1061

I read this post about using placement new to reset a boost::shared_ptr whilst avoiding additional memory allocations, and assume that the same, if not similar, can be done for a std::unique_ptr? My question is when the std::unique_ptr is of type Base* and so can point to any Derived*, will the placement new work as intended if the Derived classes vary in size? Something like this maybe:

class Base
{
public:
  Base() {}
  virtual ~Base(){}
};

class Foo : public Base
{
public:
  Foo() : Base() {}
  virtual ~Foo(){}
  int a;
  int b;
};

class Bar : public Base
{
public:
  Bar() : Base() {}
  virtual ~Bar() {}
  int a;
};

int main()
{
  std::unique_ptr<Base> bp(new Bar());
  bp->~Base(); //edit: call destructor
  void* rawP = dynamic_cast<void*>(bp.release());//edit: cast to void*
  bp.reset(new(rawP) Foo()); 
  return 0;
}
1 Answers
Related