Hacker News new | ask | show | jobs
by Galanwe 1186 days ago
> the modern practice of never using new or delete at all in C++ code

What? How do you (de)allocate memory without new and delete?

If the answer is "smart pointers" then why bother use C++ in the first place, just use Go or something.

3 comments

Go is a garbage collector. Smart pointers are not.

It's fairly simple:

instead of new --> make_unique(); this returns a pointer, but it will automatically delete its memory when it goes out of scope.

instead of delete --> do nothing; the memory is deleted when you don't need it any more.

There are additional API methods on the unique pointer that allow you to do other things for flexibility, but while continuing that memory safety.

This is nothing at all like a GC language like Go.

You allocate either on the stack, or on the heap with make_unique and make_shared. Deletion occurs automatically once the object is out of scope.
Why would you respond to a comment about a topic you don't understand and spread false information? You clearly cannot tell the difference between garbage collected language and smart pointers.
Ah, so reference counting is not considered a form of garbage collection any more? Ingenious but somewhat of dishonest.
Smart pointers do not necessarily use reference counting. std::shared_ptr is reference counted, but std::unique_ptr is not. Needless to say that std::unique_ptr should always be the default choice and std::shared_ptr only used when actually needed.
std::unique_ptr is reference counted, it's just that the count only goes up to BOOL_MAX instead of LONG_MAX.
I think you’re making a joke, but reference counting is different than what a unique pointer does. (a destructor is not the same thing as a reference count, even if that reference count is limited as you suggest.)
No, I don't think it's a joke. It's just that when your counter is limited to values of 0 and 1 only, you can optimize it so heavily it almost looks like a different thing entirely: binary semaphores are usually called mutexes, but they're still semaphores.
like the other comment said, std::unique_ptr is not ref counted. Ref counting is one of the ways to implement garbage collection but it is not garbage collection by itself. C++ does not have garbage collection.
C++ does not have garbage collection in the standard library, just as shared_ptr was not part of the standard library in the past. You can currently have optional garbage collection in C++: https://github.com/pebal/sgcl
C++ can do pretty much anything, but that doesn't mean that it’s typical to do so. In practice, you will never see a garbage collector in C++.
You may be surprised. Herb Sutter wants to add optional GC to C++ 'syntax 2'.