On 10 Feb, 16:03, mdin...@gmail.c om wrote:
Hi,
I am new to C++, and I have a simple question but I can't seem to find
a direct answer.
What you are asking might seem simple, but as soon as you scratch the
surface you will realise it is anything but. You are asking about an
advanced part of C++.
If I use new to create something in the scope of a function and then I
return the pointer that I get to another function, do I need to worry
about the memory space being used by anything else and causing the
program to crash?
No, you can be sure that the object will continue to exist until you
delete it. That is the problem. If you use new to create something in
the scope of a function and then you return the pointer that you get
to another function, you do not need to worry about the memory space
being used by anything else and causing the program to crash? But
that's the easy part. What you do need to worry about is the hard
part:
You need to be certain that in all current and likely future uses of
your function, the new'ed pointer is deleted no less than and no more
than once.
You need to be certain that any and all possibilities for copying,
modifying, passing the pointer do not violate the above point.
You need to be certain that the above two points hold, both throughout
the normal flow of execution, and in the presence of exceptions.
In short, I want to make sure that:
new reserves memory and that memory will remain intact until I
explicitly call delete, even if the scope has changed.
That is something you can be sure of. However, it should not be what
you are trying to ensure. Not calling delete until you have finished
with the object is easy. Ensuring that delete is still called, exactly
once, regardless of the path taken through the code (including the
path taken if an exception is thrown at any point) is much harder. You
should be trying to ensure that ownership semantics are clear and
unambiguous, and are not likely to introduce bugs as code is modified.
As someone new to C++, you shouldn't be worrying about manually
managing ownership. You should be using classes that manage that for
you. Read about smart pointers and the RAII concept.
Also, does the destructor of an object automatically get called at any
point or do I have to manually call it?
For objects with automatic or static storage duration (roughly, local
and global variables respectively), your compiler will take care of
calling destructors when required. For objects with dynamic storage
duration (i.e. objects allocated with new or new[]) nothing happens
automatically. You, and you alone, are responsible for ensuring that
each and every new is paired with one and only one delete, and that
each and every new[] is paired with one and only one delete[].
The need for that certainty and the difficulty in achieving it is the
reason why things like smart pointers were invented.
Gavin Deane