logoalt Hacker News

jurschreuderyesterday at 9:46 PM8 repliesview on HN

I don't know why people use 'new' and 'delete' in all the examples how memory in C++ works because you never normally use them during coding only if you want to make your own container which you might do once to learn about the internals.

C++ by default creates objects by value (opposed to any other language) and when the variable goes out of scope the variable is cleaned up.

'new' you use when you want to make a global raw pointer outside of the normal memory system is how I would see it. You really never use it normally at least I don't.

A good rule of thumb is not to use 'new'.


Replies

pjmlptoday at 7:37 AM

Unfortunately they are all over the place on corporate code.

johnnyanmacyesterday at 10:58 PM

Yes, and no?

In production, odds are you are relying on allocators or containers others already wrote. You coming in in 2026 may not ever use the keywords directly, but you'll either be using abstractions that handle that for you (be it STL or something internal) or using some custom allocation call referring to memory already allocated.

But yes, I'd say a more general rule is "allocate with caution".

unclad5968yesterday at 10:28 PM

It just makes for an easily understandable example. I don't think the post is advocating for the use of new/delete over smart pointers.

ranittoday at 12:01 AM

> I don't know why people use 'new' and 'delete' in all the examples ...

Why? Because the blog post is titled "Understanding C++ Ownership System".

show 2 replies
mikepurvisyesterday at 10:06 PM

Yup, just emplace the object directly into the container, or at worst create it by value and then add it to the container with std::move.

dupedyesterday at 10:35 PM

People use `new` and `delete` when explaining memory in C++ because those are the language primitives for allocating and releasing memory in C++.

That rule of thumb is only a useful rule if you don't care about how memory works and are comfortable with abstractions like RAII. That's fine for lots of real code but dismissing `new` and `delete` on principle is not interesting or productive for any discussion.

show 2 replies
vlovich123yesterday at 9:56 PM

And yet, I interviewed 10 people easily where I was using new and delete in the example code and only one person asked "hey - can we use unique_ptr?".

show 4 replies
mgaunardyesterday at 11:31 PM

even when you write your own container, you do not use new and delete.

show 2 replies