It depends on exactly what we mean.
- Should
new
never be used to allocate memory? Of course it should, we have no other option. new
is the way to dynamically allocate objects in C++. When we need to dynamically allocate an object of type T, we do new T(...)
.
- Should
new
be called by default when we want to instantiate a new object? NO. In java or C#, new
is used to create new objects, so you use it everywhere. in C++, it is only used for heap allocations. Almost all objects should be stack-allocated (or created in-place as class members) so that the language's scoping rules help us manage their lifetimes. new
isn't often necessary. Usually, when we want to allocate new objects on the heap, you do it as part of a larger collection, in which case you should just push the object onto your STL container, and let it worry about allocating and deallocating memory. If you just need a single object, it can typically be created as a class member or a local variable, without using new
.
- Should
new
be present in your business logic code? Rarely, if ever. As mentioned above, it can and should be typically be hidden away inside wrapper classes. std::vector
for example dynamically allocates the memory it needs. So the user of the vector
doesn't have to care. I just create a vector on the stack, and it takes care of the heap allocations for me. When a vector or other container class isn't suitable, we may want to write our own RAII wrapper, which allocates some memory in the constructor with new
, and releases it in the destructor. And that wrapper can then be stack-allocated, so the user of the class never has to call new
.
One of the articles asserted that Foo *f = new Foo();
was nearly unacceptable professional C++ code by and large, and an automatic memory management solution was appropriate.
If they mean what I think they mean, then they are right. As I said above, new
should usually be hidden away in wrapper classes, where automatic memory management (in the shape of scoped lifetime and objects having their destructors called when they go out of scope) can take care of it for you. The article doesn't say "never allocate anything on the heap" or never use new
", but simply "When you do use new
, don't just store a pointer to the allocated memory. Place it inside some kind of class that can take care of releasing it when it goes out of scope.
Rather than Foo *f = new Foo();
, you should use one of these:
Scoped_Foo f; // just create a wrapper which *internally* allocates what it needs on the heap and frees it when it goes out of scope
shared_ptr<Foo> f = new Foo(); // if you *do* need to dynamically allocate an object, place the resulting pointer inside a smart pointer of some sort. Depending on circumstances, scoped_ptr, or auto_ptr may be preferable. Or in C++0x, unique_ptr
std::vector<Foo> v; v.push_back(Foo()); // place the object in a vector or another container, and let that worry about memory allocations.