Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
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++.
-
@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.
-
@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_; -
@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.
-
@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.
Using old style C allocation in C++ be like
joke/meme