Yong Hu wrote:
Does the smart pointer never lead to memory leak?
I will explain by comparing other languages. In C++, you must build smart
pointers and manage them carefully so they don't leak. If you use a raw
pointer to a 'new' object, you manage it more carefully or it will leak.
And you can create an object without 'new', and it has much lower odds of
leaking.
The language Java was designed to be sold to your boss. The designers want
to tell your boss, "if your programmers use Java, they will never leak
memory, like that naughty C++ language lets them leak."
So Java has built-in smart pointers. You cannot write the smart pointer
with Java - it's part of the language. And all objects must use smart
pointers. No object can create without a secret call to a kind of 'new'
function, deep inside Java.
And Java also leaks memory, plenty, if you abuse it or make many kinds of
mistakes.
In general, Garbage Collection is a very tough problem, and all languages
have compromises. All languages can leak. C++, even with smart pointers,
is higher risk than most languages because C++ lets you write safe code
that goes very fast.
--
Phlip