Re: Why people use "new" & "delete" too much?!!
On Jul 5, 4:05 pm, Medvedev <3D.v.Wo...@gmail.com> wrote:
On Jul 5, 11:59 am, red floyd <no.spam.h...@example.com> wrote:
Medvedev wrote:
i see serveral source codes , and i found they almost only use "new"
and "delete" keywords to make they object.
Why should i do that , and as i know the object is going to be destroy
by itself at the end of the app
for example:
class test
{
public:
int x;
}
int main(int argc, char **argv)
{
test *n= new test;
.
.
...
delete n;
return 0;
}
i know that the object created this way is in the heap which have much
memory than stack but why they always define objects that way , why
not just say "test n" and the object will be destroyed by itself at
the end of the program! , instead of using "new" and maybe u will
forget to "delete" at the end
Several reasons.
1. They're coming from Java and they don't know any better
2. They're storing polymorphic objects inside containers
3. They need the lifetime of the object to exceed the scope in which
it was declared.
how u can use object after it's scope ends!!
Thats not what he stated. The object is _declared_ in a finite scope.
If you allocate the object on the heap, it's lifetime no longer relies
on the declaring scope.
Basicly, new and new[] transfers the responsability to you, the
programmer, to delete and delete[].
Is using new and new[] a good habit? no, its not.
You'll find C++ programmers to be retiscent in using it and would
rather rely on a smart pointer if heap allocation is indeed required.
Java programmers don't really have a choice but in C++ an automatic
variable should and usually is the default.
Generally speaking, if you see new and new[], you aren't reading a
programmer who has his roots in modern C++. Allocating on the heap
what should be automatic is frowned upon here.
And the reason for that is because smart pointers have much to offer
as long as you know their limitations.
Good examples of those are std::auto_ptr and boost::shared_ptr to name
a few.