473,789 Members | 2,431 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer to reference conversion

Hi,
This is continuation of topic pointer & reference doubt.
http://groups.google.com/group/comp....304d7d77f6ccca
But I think it is better to have a new topic rather than continuing on
old one.

As now I am sure pointer to reference and reference to pointer are
freely convertable, the potential danger lies in the first one. Pointer
may be NULL, but reference should not be.
My question is, what is the best way to answer it?
just assert that the pointer is not NULL, before dereferencing it?
However that will lead to a debug only checking. In the post
http://groups.google.com/group/comp....d52926a25a167c
Frederick Gotham had suggested an alternative method in some different
context, which throws an exception. Thus I think it is valid even at
non-debug mode and catches such potential problem at runtime.

Which one should be preferred? and any one deals with this conversion
problem in some standard way?
Going a little further, like the new operator is written throw a
bad_alloc, so one need not to check NULL pointer afrer a new (and one
can overload global new as well as specific new according to his
convenience to have some specific handler also) , can the dereferencing
operator be overloaded (globally and class specific way) to throw some
exception when one is dereferencing a NULL pointer?
Ofcouse the danger will not be fully eleminated (as one can have a
pointer which is not NULL, but points to some invalid object, like
dereferencing a pointer after delete. But such problem can be handled
with a safe_delete which sets the pointer to NULL. Or also in
conjugation with nullptr
http://www.open-std.org/jtc1/sc22/wg...2003/n1488.pdf ),
but it will get significantly removed.
Looking for some suggestions and expert comments.

Thanks

Sep 14 '06 #1
2 2845
"toton" <ab*******@gmai l.comwrote:
As now I am sure pointer to reference and reference to pointer are
freely convertable, the potential danger lies in the first one. Pointer
may be NULL, but reference should not be.
My question is, what is the best way to answer it?
just assert that the pointer is not NULL, before dereferencing it?
However that will lead to a debug only checking. In the [another] post
Frederick Gotham had suggested an alternative method in some different
context, which throws an exception. Thus I think it is valid even at
non-debug mode and catches such potential problem at runtime.

Which one should be preferred?
Dereferencing an invalid pointer (including one that is null) is an
error perpetrated by the programmer doing the dereferencing and there
isn't much that can be done after the fact to catch the error. The best
solution is to consistently make sure the pointer is not invalid before
dereferencing it, and the only way that can be done is through static
program analysis (i.e. the programmer knows at compile time that there
is no way the pointer can be invalid.)

It is possible to write a smart pointer that can monitor the program for
this problem at run-time, but there is no way for the code to ensure
that such a smart pointer is always used for all dynamic allocations,
and never used for pointers pointing to non-dynamically allocated
memory. Also such solutions tend to be rather heavy weight and tend to
get in the way of the conscientious programmer that ensures that all
pointer dereferences are valid.

The only real solution here is for the programmer(s) to pay attention to
the fundamentals. Don't ever dereference an invalid pointer.

--
There are two things that simply cannot be doubted. Logic and our
ability to sense the world around us. Doubt those, and you no longer
have anyone to discuss it with, nor any ability to discuss it.
Sep 14 '06 #2

"toton" <ab*******@gmai l.comwrote in message
news:11******** *************@p 79g2000cwp.goog legroups.com...
Hi,
This is continuation of topic pointer & reference doubt.
http://groups.google.com/group/comp....304d7d77f6ccca
But I think it is better to have a new topic rather than continuing on
old one.

As now I am sure pointer to reference and reference to pointer are
freely convertable, the potential danger lies in the first one. Pointer
may be NULL, but reference should not be.
My question is, what is the best way to answer it?
just assert that the pointer is not NULL, before dereferencing it?
I'm not sure what you mean by "the best way to answer it", but if I
understand correctly, the best way to avoid the problem is to, well, avoid
the problem. Design your app so that there is no case where you're going to
get a NULL pointer passed to code which needs it to be non-NULL.

In cases where a NULL is normal and expected, then you shouldn't be using a
reference in the first place. Doing so is an error in design, and you
shouldn't have to code around such an error.

(This is the purpose of an assert, by the way: to show you an error in your
design by catching a condition which should never occur. Unfortunately, an
assert does not _guarantee_ correct design, because it may occur in your
testing that you simply never _get_ a NULL pointer in that portion of the
code. But that doesn't mean your customers won't.)

You need to design your code correctly, avoiding situations where such a
problem could ever occur.

I don't see why you want to be switching between pointers and references in
the first place. The only place I recall seeing such "conversion s" is when
I am using pointers, but I'm calling a function in someone else's library
which expects a reference. In that case, I simply dereference my pointer.
If the pointer could _ever_ be NULL, then it's _wrong_ to call that function
in the first place (at least without checking for NULL first).

The question in such a case, then, is: what is the problem, really?

Did I make a design error? If my code assumes that that function _must_ be
called at this point, then I _must_ have made a design error, because I
allowed a NULL pointer to propogate to a place where there must never be a
NULL pointer! Time to rethink my design. Back up and see why the code
allows a NULL pointer to get here.

Alternatively, it may be that it's ok and normal for a NULL pointer to exist
at this point. In that case, my design needs to include an alternative
action for the case when the pointer is NULL. So a regular if statement is
called for, with some other action besides calling that function taken when
the pointer is NULL. Again, this is a redesign, or at least an extension to
my original design.

Notice that in neither case am I using an assert or exception to catch a
problem in testing. It's a _design_ issue at the point in time when I
notice myself writing code to dereference a pointer. Make your decision
then (if not earlier!), not when testing shows a problem, because testing
may _never_ show the problem. The problem is just as likely to bit you on
the butt after you've deployed to the field, when customers call to
complain.

If you feel you need to use assertions or exceptions, remember what they're
for: Assertions help point out design and coding problems, catching
conditions which should _never_ occur. (Well, _hopefully_ catching them!)

Exceptions are for handling _expected_ but exceptional conditions, where
you've got a design in the first place which expects that called functions
might throw, and where someone up higher in the call chain knows exactly
what to do about it. (Again, this belongs in your design stage, not as a
last-minute coding addition to try to protect against the undefined behavior
of dereferencing a NULL pointer.)

-Howard
Sep 14 '06 #3

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

Similar topics

10
2029
by: Whitney Kew | last post by:
Hello, I have a question regarding type conversion operators. Let's say I have a simple (nonsensical) class as follows: class MakeNewInt { private: int* _n;
110
9966
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object must be an object instead of
204
13123
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
53
4568
by: Tomás | last post by:
Some programmers treat arrays just like pointers (and some even think that they're exactly equivalent). I'm going to demonstrate the differences. Firstly, let's assume that we're working on a platform which has the following properties: 1) char's are 8-Bit. ( "char" is synomonous with "byte" ). 2) int's are 32-Bit. ( sizeof(int) == 4 ). 3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).
14
7189
by: Vols | last post by:
If the people ask what is the different between pointer and reference, what is the brief and good answer? I say " pointer could point to NULL, but there is no null reference", What is your opinion? Vol
21
2935
by: Chen Shusheng | last post by:
Hello, I have a small piece of code that I want to directly assign a segment of memory to a pointer. But complier tell me wrong. Pls you help.Codes below: ------------------ int * p; p=0x241ff5c; -------------------
8
2402
by: toton | last post by:
HI, One more small doubt from today's mail. I have certain function which returns a pointer (sometimes a const pointer from a const member function). And certain member function needs reference (or better a const reference). for eg, const PointRange* points = cc.points(ptAligned);
42
5348
by: xdevel | last post by:
Hi, if I have: int a=100, b = 200, c = 300; int *a = {&a, &b, &c}; than say that: int **b is equal to int *a is correct????
29
3656
by: shuisheng | last post by:
Dear All, The problem of choosing pointer or reference is always confusing me. Would you please give me some suggestion on it. I appreciate your kind help. For example, I'd like to convert a string to a integer number. bool Convert(const string& str, int* pData); bool Convert(const string& str, int& data);
0
9506
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10404
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6761
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4089
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.