Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Foo* f = new Foo good C++ code

Reading through an old C++ Journal I had, I noticed something.

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.

Is this so?

edit: rephrased: is direct memory management unacceptable for new C++ code, in general? Should auto_ptr(or the other management wrappers) be used for most new code?

like image 602
Paul Nathan Avatar asked Jan 11 '10 06:01

Paul Nathan


2 Answers

This example is very Java like.
In C++ we only use dynamic memory management if it is required.
A better alternative is just to declare a local variable.

{
    Foo    f;

    // use f

} // f goes out of scope and is immediately destroyed here.

If you must use dynamic memory then use a smart pointer.

// In C++14
{
    std::unique_ptr<Foo>  f = std::make_unique<Foo>(); // no need for new anymore
}

// In C++11
{
    std::unique_ptr<Foo>  f(new Foo);  // See Description below.
}

// In C++03
{
    std::auto_ptr<Foo>    f(new Foo);  // the smart pointer f owns the pointer.
                                       // At some point f may give up ownership to another
                                       // object. If not then f will automatically delete
                                       // the pointer when it goes out of scope..

}

There are a whole bunch os smart pointers provided int std:: and boost:: (now some are in std::tr1) pick the appropriate one and use it to manage the lifespan of your object.

See Smart Pointers: Or who owns you baby?

Technically you can use new/delete to do memory management.
But in real C++ code it is almost never done. There is nearly always a better alternative to doing memory management by hand.

A simple example is the std::vector. Under the covers it uses new and delete. But you would never be able to tell from the outside. This is completely transparent to the user of the class. All that the user knows is that the vector will take ownership of the object and it will be destroyed when the vector is destroyed.

like image 167
Martin York Avatar answered Oct 15 '22 04:10

Martin York


No.

There are very good reasons to not use automatic memory management systems in certain cases. These can be performance, complexity of data structures due to cyclical referencing etc.

However I recommend only using a raw poiner with new/malloc if ou have a good reason to not use somehting smarter. Seeing unprotected allocations scares me and makes me hope the coder knows what they're doing.

Some kind of smart pointer class like boost::shared_ptr, boost::scoped_ptr would be a good start. ( These will be part of the C++0x standard so dont be scared of them ;) )

like image 37
Michael Anderson Avatar answered Oct 15 '22 04:10

Michael Anderson