19

Using old style C allocation in C++ be like

Comments
  • 0
    Why TF are you using malloc? Unless you're interop-ing with a C library that needs you to allocate (that's a shitty library if so) then you should *never* be using malloc in C++.
  • 0
    @Demolishun Right so you're using a C lib. That's what I said lol.
  • 0
    @Demolishun I said neither of those things.
  • 1
    @Demolishun No, you don't. Use:

    alignas(T*) char *inst_ = new char[sizeof(T)];
    auto inst = new (reinterpret_cast<T*>(inst_)) T(...);

    inst->T::~T();
    delete[] inst_;
  • 1
    @Demolishun If you do have to get an instance without calling the constructor that's definitely a shitty library though. Also, having user code construct objects of your internal types isn't ideal, although for structs with trivial lifetime it should be okay. Otherwise opaque pointers are preferable.
  • 0
    AND I WILL MAKE YOUR FACE THE GREATEST IN DEVRANT
  • 2
    @Demolishun Placement new doesn't allocate memory but uses existing one.
Add Comment