473,737 Members | 8,878 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pass-by-reference instead of pass-by-pointer = a bad idea?

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

void func(Object* object); //object can be NULL

I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.

Any comments on why this could be a bad idea or do you think it's just
a matter of taste?

/H
Jul 23 '05 #1
110 9940
Mr A wrote:
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

void func(Object* object); //object can be NULL

I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.

Any comments on why this could be a bad idea or do you think it's just
a matter of taste?

/H


That is exactly the right way to do it. I'd go so far as to say always
prefer a reference over a pointer unless you have an explicit need for a
pointer (i.e. it needs to be reseated for some reason and/or NULL has a
useful meaning). The reason being pretty much the same that you stated.
References are (for me at least) easier to work with, and there is no
worry of accidentally trying to access an object through a "NULL reference".

-Alan
Jul 23 '05 #2
Mr A wrote:
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

void func(Object* object); //object can be NULL

I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.

Any comments on why this could be a bad idea or do you think it's just
a matter of taste?

/H


Unfortunately, there are different vantage points from which we view a
function: declaration, definition and invocation. Each has it's own
exposed and hidden information. It has been argued that passing a pointer
is more explicit, and makes the code easier to read. I tend to agree.

AFAIK, you *can* pass a null to func() in your example, and the compiler
will accept it. Your code will segfault when you do so. If you pass a
pointer, you can check for null, before accessing it. I, therefore,
suggest using a pointer instead of a reference.
--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Jul 23 '05 #3
Steven T. Hatton wrote:
Mr A wrote:
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

void func(Object* object); //object can be NULL

I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.
The above paragraph is correct. Attempting to pass ANYTHING except
a ref to an existing instance of the required type will cause a
compile-time error. Unless there is some specific reason to pass a
pointer, using ref's is usually preferred.

Any comments on why this could be a bad idea or do you think it's just
a matter of taste?

/H


Unfortunately, there are different vantage points from which we view a
function: declaration, definition and invocation. Each has it's own
exposed and hidden information. It has been argued that passing a pointer
is more explicit, and makes the code easier to read. I tend to agree.

AFAIK, you *can* pass a null to func() in your example, and the compiler
will accept it. Your code will segfault when you do so. If you pass a
pointer, you can check for null, before accessing it. I, therefore,
suggest using a pointer instead of a reference.


If a function takes a ref, then NULL can not be passed.
Attempting to pass NULL causes a compile error.
For example:

#include <iostream>

struct Stuff
{
int a;
double b;
};

void func(Stuff& obj)
{
obj.a = 1;
}

int main()
{
Stuff s;

func(s);
func(0); // causes a compile error

return 0;
}

Larry
Jul 23 '05 #4
Larry I Smith wrote:
Steven T. Hatton wrote:
Mr A wrote: [...]
I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.
The above paragraph is correct. Attempting to pass ANYTHING except
a ref to an existing instance of the required type will cause a
compile-time error. Unless there is some specific reason to pass a
pointer, using ref's is usually preferred.


By whom?
Any comments on why this could be a bad idea or do you think it's just
a matter of taste?

/H


Unfortunately, there are different vantage points from which we view a
function: declaration, definition and invocation. Each has it's own
exposed and hidden information. It has been argued that passing a
pointer is more explicit, and makes the code easier to read. I tend to
agree.

AFAIK, you *can* pass a null to func() in your example, and the compiler
will accept it. Your code will segfault when you do so. If you pass a
pointer, you can check for null, before accessing it. I, therefore,
suggest using a pointer instead of a reference.


If a function takes a ref, then NULL can not be passed.
Attempting to pass NULL causes a compile error.
For example:

#include <iostream>

struct Stuff
{
int a;
double b;
};

void func(Stuff& obj)
{
obj.a = 1;
}

int main()
{
Stuff s;

func(s);
func(0); // causes a compile error

return 0;
}

Larry


In your example, you are not trying to pass null, you are trying to pass a
literal. That results in the attempt to create a temporary object of type
int and assign it to the non-const reference. This, however, will compile:

#include <string>
std::string func(std::strin g& s) { return s; }
int main() {
std::string* s(0);
func(*s);
}

I know of two companies who have concluded that passing by reference is, in
general, a bad choice. Trolltech, and SuSE.
--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Jul 23 '05 #5
"Steven T. Hatton" <ch********@ger mania.sup> wrote in message
news:as******** ************@sp eakeasy.net

In your example, you are not trying to pass null, you are trying to
pass a literal.
He is passing NULL which is the same as 0.
That results in the attempt to create a temporary
object of type int and assign it to the non-const reference. This,
however, will compile:

#include <string>
std::string func(std::strin g& s) { return s; }
int main() {
std::string* s(0);
func(*s);
}


Dereferencing a NULL pointer is undefined behaviour by section 8.3.2/4.
When I run your code, the program crashes.

--
John Carson

Jul 23 '05 #6
"Steven T. Hatton" <ch********@ger mania.sup> wrote in message
news:as******** ************@sp eakeasy.net

AFAIK, you *can* pass a null to func() in your example, and the
compiler will accept it. Your code will segfault when you do so.
If you pass a pointer, you can check for null, before accessing it.
I, therefore, suggest using a pointer instead of a reference.


I missed this bit. It seems you are aware of the problem.

--
John Carson
Jul 23 '05 #7
Steven T. Hatton wrote:
Larry I Smith wrote:
Steven T. Hatton wrote:
Mr A wrote: [...]I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.

The above paragraph is correct. Attempting to pass ANYTHING except
a ref to an existing instance of the required type will cause a
compile-time error. Unless there is some specific reason to pass a
pointer, using ref's is usually preferred.


By whom?
Any comments on why this could be a bad idea or do you think it's just
a matter of taste?

/H

Unfortunately, there are different vantage points from which we view a
function: declaration, definition and invocation. Each has it's own
exposed and hidden information. It has been argued that passing a
pointer is more explicit, and makes the code easier to read. I tend to
agree.

AFAIK, you *can* pass a null to func() in your example, and the compiler
will accept it. Your code will segfault when you do so. If you pass a
pointer, you can check for null, before accessing it. I, therefore,
suggest using a pointer instead of a reference.


If a function takes a ref, then NULL can not be passed.
Attempting to pass NULL causes a compile error.
For example:

#include <iostream>

struct Stuff
{
int a;
double b;
};

void func(Stuff& obj)
{
obj.a = 1;
}

int main()
{
Stuff s;

func(s);
func(0); // causes a compile error

return 0;
}

Larry


In your example, you are not trying to pass null, you are trying to pass a
literal. That results in the attempt to create a temporary object of type
int and assign it to the non-const reference. This, however, will
compile:

#include <string>
std::string func(std::strin g& s) { return s; }
int main() {
std::string* s(0);
func(*s);
}

I know of two companies who have concluded that passing by reference is,
in
general, a bad choice. Trolltech, and SuSE.

Obvious exceptions are:

std::ostream& print(std::ostr eam& out) const {...}

and when passing a const reference:

int foo(const BigObject& bo){}
--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Jul 23 '05 #8
John Carson wrote:
"Steven T. Hatton" <ch********@ger mania.sup> wrote in message
news:as******** ************@sp eakeasy.net

In your example, you are not trying to pass null, you are trying to
pass a literal.


He is passing NULL which is the same as 0.


'0', when it appears in your code, is a literal. If the reference were
const, the code /would/ compile.

#include <string>
std::string cfunc(const std::string& s) { return s; }
int main() {
cfunc(0);
}

It still has a problem. The above aborts when executed. That's one better
than a segfault, but not typically what I want from a program.
That results in the attempt to create a temporary
object of type int and assign it to the non-const reference. This,
however, will compile:

#include <string>
std::string func(std::strin g& s) { return s; }
int main() {
std::string* s(0);
func(*s);
}


Dereferencing a NULL pointer is undefined behaviour by section 8.3.2/4.
When I run your code, the program crashes.


Yes, it segfaults. That was my point.

--
If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true.-Bertrand Russell
Jul 23 '05 #9
Mr A wrote:
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

void func(Object* object); //object can be NULL

I belive that this is a good idea since , in the reference case, it's
clear that NULL is not an option. It's also clear that NULL is an
option when a pointer is expected (stating the obvious :-) ). The code
becomes somewhat more self-documenting.

Any comments on why this could be a bad idea or do you think it's just
a matter of taste?


That looks like a very good idea to me, and IIRC, the FAQ agrees. IMHO,
it's more than a matter of style; it's also a matter of safety. If a
parameter should never be null, then don't give it the chance.

Kristo
Jul 23 '05 #10

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

Similar topics

7
2075
by: winlinchu | last post by:
Hi! I use Python, and writing some extension modules I think which could be written an C compiler, useful only to compile extension modules (I not think an GCC!!!!), so that the user not have to use GCC, Microsoft Visual C++, or other. It must have an common API to all platforms, even if obviously the implementation is various. Could be write in 100% Python pure.
29
1958
by: Jim Hubbard | last post by:
Yet another hotfix alert (http://www.kbalertz.com/Feedback_823535.aspx) that states "To resolve this problem immediately, contact Microsoft Product Support Services to obtain the hotfix." Whatever happened to automatic updates? Doesn't Microsoft know that developers are busy people.....too busy to be stopped by this type of crap every time Microsoft is alerted to something they missed in the software by another developer (note:...
13
2579
by: Bryan Parkoff | last post by:
You may notice that switch (...) is much faster than function that can gain a big improved performance because it only use JMP instruction however function is required to use CALL, PUSH, and POP instruction that can be slower. I created three functions in an array. Array is called pArray_Func(). pArray_Func() contains three functions. "xx" can be used to point each function. Let say, I have over 1,000 functions. I would put "inline"...
25
10406
by: dixie | last post by:
I have some code that adds new records into a table for each ID in a list box when a button on a form is clicked. This works fine. My problem now is that I wish to be able to edit all the records for people whose ID is in the list box. I made minor changes to the code (mainly replacing rs.AddNew with rs.Edit)and it appears to be updating only the first record and then overwriting that record with the next, etc until it runs out of ID's...
19
3608
by: Raposa Velha | last post by:
Hello to all! Does any of you want to comment the approach I implement for instantiating a form? A description and an example follow. Cheers, RV jmclopesAThotmail.com replace the AT with the thing you know ;-) After discovering that access 2000 support form properties (I'm a
7
1758
by: Alan Silver | last post by:
Hello, I would like to create a new web site with VWD, but would like to run it under IIS, not the development server. One reason for this is that I want the web site to be at the domain root, not under a virtual directory. I have tried this, but don't seem to be able to get it to work. I created a new (empty) web site in IIS, and then started a new project in VWD and specified the type as HTTP. I browsed to http://test/ and
4
6723
by: Pedro Leite | last post by:
Good Afternoon. the code below is properly retreiving binary data from a database and saving it. but instead of saving at client machine is saving at the server machine. what is wrong with my code ?? thank you Pedro Leite From Portugal ------------------------------------
12
1812
by: Paul H | last post by:
A little off topic this one because the database may not be written in Access. I am just looking for some advice.. I have an idea to help prevent a particular type of crime, a database will be involved in storing and analysing information. The idea is quite a simple one and once disclosed would be easy, with reasonable technical know-how, to set-up. Police forces all over the country could use my system, but I want to approach the...
32
2701
by: andresj | last post by:
I was doing some programming in Python, and the idea came to my mind: using fractions instead of floats when doing 2/5. The problem arises when you try to represent some number, like 0.4 in a float. It will tell you that it's equal to 0.40000000000000002. "This is easy to fix", you may say. "You just use the decimal.Decimal class!". Well, firsly, there would be an excess of typing I would need to do to calculate 0.4+0.6: from decimal...
0
8968
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8786
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
9334
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...
1
9258
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9207
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...
0
8207
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6749
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
6052
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();...
3
2192
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.