-2

In C++, I have two block of codes like this:

Base *base = new Base();
base->showName();

And:

Base base;
base.showName();

I don't know when do we use pointer and when not? And what's different and what is better?

Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86

1 Answers1

8

The first code you showed is a memory leak.

The second snippet is Java, not C++. The question has been edited to use my suggested code.

Generally though, in C++ you should avoid new unless you really NEED dynamic lifetime. Instead, write:

Base base;
base.showName();

This is better because

  • It's faster, no heap allocation needed.
  • You don't have to remember to free the memory, the compiler does that automatically at the end of the scope.
  • It's automatically exception safe. The destructor will be called, and the memory will be recovered, during stack unwinding.

If the object needs to live past the end of the scope, you should be using:

unique_ptr<Base> base(new Base());
base->showName();

Now unique_ptr will free the memory for you when the unique_ptr dies, and it's also exception-safe. When you return a unique_ptr, ownership is transferred to the caller, and he can reap the benefits of automatic cleanup.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • why the first block is memory leak? I compiled, and it's ok! – Kingfisher Phuoc Jun 09 '12 at 15:46
  • 3
    Just because it compiles, doesn't mean its "OK". – John Dibling Jun 09 '12 at 15:50
  • Yeap! What will happen if i have a fucntion: `doSomething()` and in this function i create `Base *base = new Base()`, and i don't delete `*base` after using. If in `main()`, i use `doSomething()`, do i get a memory leak?! – Kingfisher Phuoc Jun 09 '12 at 15:58
  • 1
    @Kingfisher, I'd really recommend reading the link posted in the comments. You have a memory leak when you allocate space for it on the heap, but never deallocate it, so it just sits there unusable by anything else the whole time. – chris Jun 09 '12 at 15:59