473,320 Members | 1,887 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Re: Is this reference declaration legal?

jl*****@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?
Yes, certainly.
>
// Do stuff with ref here.

delete(ptr);
Actually 'delete' is an operator, not a function. The parens are
superfluous.
ptr = NULL;
There is really no need for that.
return;
}

Ordinarily I'd say this is legal, but I haven't read any
documentation that explicitly says so.

(Now, I understand that it's bad form to allocate memory and free/
delete it in the very same scope,
Why?
but I just want to know if it's okay
to declare a reference to a (de-referenced) pointer, assuming the
pointer points to a valid object and that the reference is not used
after the memory is freed/deleted.)
Yes, it is.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #1
3 1561
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.netwrote:
>
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
Jun 27 '08 #2
jl*****@hotmail.com wrote:
>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.netwrote:
>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.
That would require pretty big stack, for one. OTOH, if it's an array
you want whose size needs to be determined at run-time, you have no
other choice but to use dynamic memory. You have mechanisms that help
you like 'std::vector' or 'std::deque', or you can roll your own, but
those arrays aren't on the stack, that's for sure. And they allocate
their memory and free/delete it in the "very same scope", only without
actually exposing those operations.
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #3
jl_p...@hotmail.com wrote:
>
> (Now, I understand that it's bad form to allocate memory and free/
delete it in the very same scope,
On Jun 27, 2:08 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>
Why?
jl_p...@hotmail.com wrote:
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.
On Jun 27, 2:08 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>
That would require pretty big stack, for one. OTOH, if it's an array
you want whose size needs to be determined at run-time, you have no
other choice but to use dynamic memory. You have mechanisms that help
you like 'std::vector' or 'std::deque', or you can roll your own, but
those arrays aren't on the stack, that's for sure. And they allocate
their memory and free/delete it in the "very same scope", only without
actually exposing those operations.

You're right, of course. std::vectors and std::strings do use
pointers and memory allocation/deallocation under the hood, but that's
not what Bjarne Stroustrup (and I) want to avoid.

std::string and std::vectors (and other STL containers, I'm sure)
use memory allocation & deallocation, but they do so transparently, so
the programmer who uses them does not have to worry about it. The
containers are written so that they are self-cleaning (in that they
clean themselves when they go out of scope), relieving the programmer
who uses them of having to do any pointer maintenance on them.

When you use a pointer in the way that Stroustrup said you
shouldn't, like this:

void fct() // ugly, error-prone, and inefficient
{
X* p = new X;
// use p
delete p;
}

you have to:

a) remember to delete p at the end of the scope
b) remember to delete p if ever the function is prematurely exited
c) make sure p is never free()d (or deleted if malloc()ed)

and if you do allocate memory for a pointer that is meant to live
outside its scope, you still have to:

d) make it clear whose responsibility it is to free/delete the memory
e) make sure the memory really IS freed/deleted
f) make sure p is never deleted more than once

and if you are a programmer and are dealing with a buggy section of
code that uses a pointer, you still have these potential problems to
consider:

g) you may not necessarily know if the memory you're pointing to was
properly initialized
h) you may not necessarily know if the memory you're pointing to has
already been freed/deleted
i) you won't necessarily know if the pointer you have points to just
one instance of an object, or just the first element of an allocated
array of objects
j) if you have a pointer that you know points to the first element of
an allocated array of objects, you have no way of knowing when you go
out of the array bounds unless the original programmer was kind enough
to provide that information for you

(And for the record, I've seen ALL of these happen, and I've had to
fix all of them at least once.)

But if you use the alternatives C++ provides you (such as
std::strings, std::vectors, references, and declaring objects on the
stack), you'll never have to worry about those issues. For example,
if you avoid the manual memory allocation of an object (using new or
malloc()), you don't have to worry about double-freeing memory -- in
fact, you don't have to worry about de-allocating memory at all! STL
objects (declared on the stack) will do it for you so you don't have
to.

I encourage C++ programmers to avoid using the '*' operator in
their code (unless, of course, it's for multiplication). Doing so
avoids many headaches associated with pointers (like memory leaks and
crashes associated with pointers) as well as simplifies many aspects
of their code (like rarely having a need to write an operator=()
method or destructor for their classes).

Sure, the STL classes often use pointers "under the hood," but they
are used in STL classes transparently so that you don't have to
manipulate the pointers manually. When I encourage C++ programmers
not to use pointers, I don't mean not using classes and structures
that use pointers; I mean only using structures that are self-cleaning
-- and avoiding declaring pointers and manual allocation/deallocation
of memory.

Relying on objects declared on the stack (even if they are STL
containers) and not on manually allocated memory almost always results
in cleaner and less error-prone code. (And in many instances results
in faster, more efficient code as well.)

I hope this clarifies things, Victor.

Have a great weekend!

-- Jean-Luc
Jun 27 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Chris Johnson | last post by:
Greetings all: I come across an interesting question (to me anyway) and I do not know the answer. Code/Questions follow: #include <iostream> #if 0 // uncommenting *should* make call...
17
by: Michael Sparks | last post by:
In this code, the temporary inside_t instantiated in main() goes out of scope by the time we hit the next line. MSVC 2003 doesn't complain about that even at the highest warning level. Is it...
3
by: Ed J | last post by:
I'm trying to port some C++ code from MS Visual Studio 6.0 to a version of Code Composer Studio for an embedded application. This code compiles under Visual Studio, and lets the program reference...
6
by: Senthilvel | last post by:
Hi folks, My friend tells that the following function declaration is illegal. void Foo(const string& strData = "Default"); My friend argues that it is not legal to provide a default value for...
6
by: Teddy | last post by:
Hello all simple code below: void foo() { } void foo(int i = 0) { } int main() { //foo(); // call of overloaded 'foo()' is ambiguous
3
by: b83503104 | last post by:
Hi, I wonder if this is a legal array declaration? const int size = 5; double array; Or should I use "new"? Thanks.
8
by: Michael Safyan | last post by:
Dear members of comp.lang.c++, I am a little bit confused about the differences between constant references and values. I understand that it is faster to use a constant reference ("const T&") than...
3
by: arnuld | last post by:
1) int i = 3; 2.) int* pi; 3.) int* pi2 = &i 4.) char* pc; 5.) char c; 6) char c2 = 'a' 7.) char* pc2 = &c2 8.) char* ps = "Stroustroup"; 9.) extern double d;
5
by: Vols | last post by:
class A{ public: int x; }; class B : public A{ public: int y; }; void foo()
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.