> jl_p...@hotmail.com wrote:
> > I've wondered for quite some time if it's legal to make a reference
> > to a pointer, like this:
>
> > void f()
> > {
> > SomeClass *ptr = new SomeClass;
>
> > SomeClass & ref = *ptr; // is this legal?
On Jun 27, 10:39 am, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
>
> Yes, certainly.
Thanks for your response, Victor, I appreciate it.
> > (Now, I understand that it's bad form to allocate memory and free/
> > delete it in the very same scope,
>
> Why?
Because if it's all in the same scope, there's no need to declare
it as a pointer and allocate it memory. Just declare it on the stack
(as a non-pointer) and let it clean itself up.
This is described with more in detail at Bjarne Stroustrup's C++
Style and Technique FAQ at:
http://www.research.att.com/~bs/bs_faq2.html
under the question "Why isn't the destructor called at the end of
scope?"
Basically, what Stroustrup has to say about it is that "Code that
creates an object using new and then deletes it at the end of the same
scope is ugly, error-prone, and inefficient." While he uses
subjective language (like "ugly"), I happen to agree with him, for I
believe that memory that is allocated and freed/deleted in the same
scope has no reason not to be declared on the stack.
But if you feel I'm wrong about that, I'd like to hear your opinion
on the matter.
(Plus, I generally encourage C++ programmers to program with as few
pointers as possible. In my experience, about 90 to 95% of all
pointers I come across in C++ can easily be done away with by
replacing them with objects declared on the stack, std::strings,
std::vectors, and/or references.
And since about 95% of program crashes involve mis-handled pointer
memory (again, this is in my experience), eliminating most (if not
all) pointers in code will eliminate around 90% of crashes and
drastically improve correctness and, in my opinion, readability (as
code can now follow closer to pseudocode and not have as many
programming-language dependent extras like explicit memory frees).
Many C++ programmers don't realize that a lot of pointer handling
is unnecessary in C++ as C++ offers simple ways around most pointer
usage. So for these reasons I often challenge C++ programmers to
program without pointers. (Which, sadly, often ends in heated debates
where a programmer refuses to give up programming with pointers saying
it is impossible to do so. And when I show them it can be done, they
proclaim that they use pointers for efficiency, only to resent it when
I show them that the non-pointer solution is usually faster.
Thankfully, not all programmers are this way, but unfortunately some
are.))
Anyway, sorry for getting off-topic. And again, thanks for your
help, Victor.
Have a great week!
-- Jean-Luc