So I first learned Java and now I\'m trying to switch over to C++. I\'m having a little difficulty getting arrays to work correctly.
Right now I am simply trying to crea
In Java, you do Foo f = new Foo();
, giving you a dynamically allocated object who's lifetime is managed by the garbage collector.
Now, in C++, Foo* f = new Foo;
looks similar and also gives you a dynamically allocated object (which you can access via the pointer f
), but C++ doesn't have a built-in garbage collector. In most cases, the functional C++ equivalent is Foo f;
, which gives you a local object that is destroyed when you leave the current function (via return or throw).
If you need dynamic allocation, use "smart pointers", which are actually classes that behave like pointers. In C++ 98, there is only std::auto_ptr
and people often use boost::shared_ptr
to complement it. In the newer C++ 11, there are std::unique_ptr
and std::shared_ptr
that achieve the same.
I hope this gives you some pointers in directions where you need to read a bit, but overall Juanchopanza gave a good advise: Don't use new
unless you really need to. Good luck!