Solved

References & Effeciency

Posted on 2003-10-29
11
257 Views
Last Modified: 2011-09-20
How do references work under the hood (without getting too technical)?

What's better as a function argument:

const myobj& val OR const myobj val

when myobj contains a single char as a data member? Copying one char likely has less overhead than passing a pointer to myobj (which will likely be a 4 byte pointer) but what about references? Is there an overhead to using them or are they more like an alias for an existing variable?

Curious,
-Sandra
0
Comment
Question by:Sandra-24
  • 3
  • 2
  • 2
  • +3
11 Comments
 
LVL 10

Expert Comment

by:Sys_Prog
ID: 9647720
A refernce is just an alias for some variable.

Thus it is always better to pass by reference


When u pass by value, a new variable is created while when u pass by reference, a new variable is not created, it is somewhat like a const pointer.

0
 
LVL 10

Expert Comment

by:Sys_Prog
ID: 9647772
And u should always pass by a const reference if u do not wish to modify the argument

0
 
LVL 15

Accepted Solution

by:
efn earned 100 total points
ID: 9648014
> How do references work under the hood (without getting too technical)?

Typically, like constant pointers that are automatically dereferenced.

>What's better as a function argument:

> const myobj& val OR const myobj val

> when myobj contains a single char as a data member?

If the myobj class has any virtual functions, the first one is likely to be more efficient.  The second form is somewhat pointless.  Since the called function is getting a copy of the object anyway, there is usually no reason to care if the function modifies the object.  Otherwise, there is not much difference.

>  Copying one char likely has less overhead than passing a pointer to myobj (which will likely be a 4 byte pointer) but what about references?  Is there an overhead to using them or are they more like an alias for an existing variable?

Semantically, a reference is like an alias.  The compiler is not likely to mess around with anything smaller than a machine word, so there is not likely to be any difference between passing a char and a pointer.  The cost of a reference parameter is likely to be the same as the cost of a pointer parameter.

I'm using all these "likely"s because these are matters of implementation not specified by the language standard, so it's hard to say definitively how all compilers are implemented.  I'm just giving you my understanding of how it's usually done.

The way to get a definitive answer for a specific compiler is to look at the code it generates.  Unfortunately, you have to understand assembly language to do that.

--efn
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 3

Expert Comment

by:EarthQuaker
ID: 9650535
A ruleset I have is :

Use references when you can.
Use pointers when you must.

Don't use reference on basic primitive type such as int/char etc.
Don't use pointers on basic primitive type such as int/char etc. appart  when the goal is to pass an array ( of course ).

Have a read on :

http://www.tantalon.com/pete/cppopt/asyougo.htm#PassClassParametersByReference
0
 
LVL 3

Author Comment

by:Sandra-24
ID: 9654193
So do you treat a object with a single primitive type data member as a primitive type? Or do you treat it as an object and pass it by reference?

And you mention const pointers. I didn't realize they were implemented differently than regular pointers. I suppose they have been replaced by references in C++ though, I don't see any point to their use.
0
 
LVL 7

Expert Comment

by:burcarpat
ID: 9654966

  http://www.boost.org/libs/utility/call_traits.htm

check out call_traits<T>::param_type.  this construct figures out if you need to pass the parameter as it is or by ref.  it requires a newer compiler to work but when it works, it's really very handy.  i use it whenever i have a template parameter but it doesn't hurt to use it always ( although it will make your compile time longer )

-- ba
0
 
LVL 15

Expert Comment

by:efn
ID: 9655193
I don't think const pointers are implemented differently from other pointers.  The const qualifer just gives you a compile-time check so the compiler can point it out if you try to change something you previously said you would never change.

You might make a pointer constant for the same reason as anything else:  you think it should never change, so if some code appears that tries to change it, you want the compiler to notify you.

--efn
0
 
LVL 7

Expert Comment

by:burcarpat
ID: 9655269
the problem with const pointers is,

  const int*

and

  int* const

mean different things and that might cause some confusion.  other than that, pointers and const pointers are just the same

-- ba
0
 
LVL 2

Expert Comment

by:MirkoLMV
ID: 9660998
References are presented as aliases of variables. The materials that I have studied until now suggest that references are a sort of constant pointers with particular behavior. The main particular aspect of references is the replacing of dereferencing with classic assignment operation, thus obtaining the indirect access by using the classic simpler syntax of the direct access. The gain is that source code becomes more simple, easier to understand and with a reduced risk of error.

Use of reference for atomic types (character, integer varieties, booleans, float varieties) is usually less efficient than simple pass of the value, because of the indirect access performed. There could be some cases of complex processing and special interest in access limitations to some variables of a very high importance.

An Object can be treated as a primitive type only when using overloaded operators. Otherwise, member access expressions (with dot and arrow operators) are required.

Constant pointers cannot be replaced by references when used as identifiers for a block of dynamically allocated memory area (usually an array). There are situations when some data can be handled just by pointers and then only a constant pointer can be used for a restricted access.

Good luck !
0
 
LVL 3

Author Comment

by:Sandra-24
ID: 9661002
I did some research and tested a few things in code.

A const pointer (where the pointer itself is defined as const, not the object it points to) is 4 bytes on my system.

It will likely be 8 bytes on a 64bit platform.

A reference is also 4 bytes.

So passing a reference to an object containing a single basic type member is likely more expensive than simply passing by value.

As long as the copy constructor is inline that is (otherwise you have the overhead of the function call I'd imagine).

For objects just consisting of a single basic type data member and some (non-virtual) members you can apply the same rules when passing it into a function as you would for that basic type. Pass it by value.
0
 
LVL 10

Assisted Solution

by:Sys_Prog
Sys_Prog earned 25 total points
ID: 9661988
If u pass any type of a variable by value, as I posted already, a new copy is created in memory

A normal habit when passing an argument to a function should be to pass by const reference. Although at first this may seem like only an efficiency concern (and you normally don’t want to concern yourself with efficiency tuning while you’re designing and assembling your program), there’s more at stake: a copy-constructor is required to pass an object by value, and this isn’t always available.

The efficiency savings can be substantial for such a simple habit: to pass an argument by value requires a constructor and destructor call, but if you’re not going to modify the argument then passing by const reference only needs an address pushed on the stack.

In fact, virtually the only time passing an address isn’t preferable is when you’re going to do such damage to an object that passing by value is the only safe approach (rather than modifying the outside object, something the caller doesn’t usually expect).

0

Featured Post

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question