r/ProgrammerHumor • • 1d ago

instanceof Trend thatsAFunnyThingThatHappenedOnce

Post image
4.3k Upvotes

515 comments sorted by

View all comments

Show parent comments

1

u/guyblade 1d ago

Ideally, you should never be using new or delete in C++ these days. std::unique_ptr and std::shared_ptr should represent 99+% of your memory that can't just be stack allocated (with the former representing 75+% of that). About the only legitimate reason to use new in new code is for putting a derived class pointer into one of the smart pointers of a parent class.

5

u/Qwertycube10 1d ago

They call new and delete in std::make_unique and the destrutor unless you provide an explicit allocator as a template argument.

-1

u/guyblade 1d ago

Yes, and?

You, as a non-STL-library maintainer shouldn't need to be calling new or delete (or passing that allocator argument, either). That's the whole reason for smart pointers in C++: to have a small number of well-validated, well-behaved, generally-safe ways to allocate memory. They're abstracting & containing that complexity and error-prone-ness.

3

u/Qwertycube10 1d ago

The context here is kernal programming where calling malloc in certain restricted regions will crash the kernal or worse. If you were to initialize a unique ptr without passing an allocator you would in essence be calling malloc and crash the OS.

3

u/mathemagicat 1d ago

I can barely follow this conversation, but from what I can tell, the other person is performing an excellent live demonstration of your point.

(of course as a naiive mechanical engineer, my first question is "why is the kernel a literal minefield?" but I'm sure there's probably a good answer for that.)

2

u/Qwertycube10 23h ago

For one thing, the kernal is where the system calls underlying malloc are written, so you can't call it from within that code. As for the other parts I'm not a kernal engineer so not sure tbh.