20

Using old style C allocation in C++ be like

Comments
  • 0
    Using new style casts be like...carpal tunnel
  • 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
    @junon Because I don't have time to rewrite open62541... Its a C lib for opcua.
  • 0
    @Demolishun Right so you're using a C lib. That's what I said lol.
  • 0
    @junon Why is it shitty? Is the Linux kernel shitty?
  • 0
    @Demolishun I said neither of those things.
  • 0
    @junon Also, if you ever need to allocate memory for a class/object and DONT want the constructors/destructors to be called then you can allocate that memory using malloc. Not sure if there is ever a situation that calls for that though. The closest thing I have seen to that is in place new, but that still calls constructors. Eh, another tool in the toolbox for obscure needs.
  • 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
    @Lor-inc I think my favorite use of malloc is trolling c++ devs. I think the last time I used malloc was in the 90s.
  • 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