-4

When I create a new object with a pointer in C++, I need to delete it when finished or when I move this pointer to another object to avoid a memory leak. Does new Some_Object in Java work like that?

Some_Object o1 = new Some_Object("oj1");
o1 = new Some_Object("oj2");  // do this make memory leak in Java?
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
dante
  • 283
  • 1
  • 4
  • 11
  • in c++, if you assign an object created with new to a pointer, and then point that pointer elsewhere, you have leaked the memory unless you have another reference to the created object elsewhere. – JGroven Apr 16 '17 at 01:24
  • 5
    C++ is not Java. – Kerrek SB Apr 16 '17 at 01:25
  • 3
    Not it does not leak memory. The Garbage Collector in java is pretty reliable. What you can have is resource leaks (sockets, streams left open) – efekctive Apr 16 '17 at 01:27
  • 2
    There are ways, though that memory can leak in Java. See this extensive SO thread on the topic: http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java – Paul T. Apr 16 '17 at 01:54
  • 1
    In C++ you don't have to use `new` to create an object. – Bo Persson Apr 16 '17 at 03:43

2 Answers2

9

In short, no. Java has a built-in (and mandatory) garbage collector. C++ does not.

Once an Object is no longer reachable (in Java), it is eligible for garbage collection (and the collector may free the memory).

Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
3

A "memory leak" in a memory-managed language like Java doesn't have exactly the same meaning as it does in C++ because Java doesn't require you to explicitly free memory that you've allocated.

With that said, you can have basically the same effect through. Collection classes and implementations of the Observer Pattern tend to be a major culprit in this regard. One of the consequences of memory management is that if any object holds a reference to an object, the object will stay in memory whether you intend to use it again or not. This can result in objects staying around in memory much longer than necessary (perhaps even for the duration of the program).

You can also run into problems if you refer to unmanaged objects. There are a number of possible solutions to this; for example, C# solves this with the Dispose Pattern. The fact is, though, introducing unmanaged object makes it possible that you will end up with an actual memory leak.

EJoshuaS - Reinstate Monica
  • 10,460
  • 46
  • 38
  • 64