References & Effeciency

Posted on 2003-10-29
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?

Question by:Sandra-24
  • 3
  • 2
  • 2
  • +3
LVL 10

Expert Comment

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.

LVL 10

Expert Comment

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

LVL 15

Accepted Solution

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.


Expert Comment

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 :

Author Comment

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.
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.


Expert Comment

ID: 9654966

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
LVL 15

Expert Comment

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.


Expert Comment

ID: 9655269
the problem with const pointers is,

  const int*


  int* const

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

-- ba

Expert Comment

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 !

Author Comment

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.
LVL 10

Assisted Solution

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).


Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

708 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now