Confused with object arrays in C++

前端 未结 7 667
后悔当初
后悔当初 2021-01-30 03:56

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

7条回答
  •  温柔的废话
    2021-01-30 04:10

    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!

提交回复
热议问题