References & Effeciency

Posted on 2003-10-29
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 400 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.

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


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.

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 100 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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.
Suggested Courses

752 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