473,513 Members | 4,022 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

constant references?

What it the use of constant references in methods and functions? Is it a
design issue or hwat?

A reference that cannot be edited? huh?
Why pass a reference then?
Jul 22 '05 #1
8 2451
Rickard Andersson wrote:
What it the use of constant references in methods and functions? Is it a
design issue or hwat?

A reference that cannot be edited? huh?
Why pass a reference then?


At least one example of when constant references are useful is the case
when you want to pass an object as a read only parameter to some function:
class A
{
// add members here
}

void foo(const A& a)
{
// access a thru read only operations
}

By declaring the parameter 'a' as a const refernce you tell users of
foo() that their object won't be altered as a result of the call to
foo(). You also enable clever compilers to make assumptions on how 'a'
will be used inside foo() and based on that they might be able to do
some optimisations when compiling your code. Last but not least, if the
size of A should large you will avoid passing the whole object and
instead pass a suposedly much smaller reference.

:.:: mattias

Jul 22 '05 #2
Okay, how do I know when I should pass a const reference and not a simple
const?

Dummy question, but it's confusing to me!

btw, you're swedish living in Luleå? :-)
"Mattias Brändström" <br****@ludd.luth.se> skrev i meddelandet
news:3f*********************@news.luth.se...
Rickard Andersson wrote:
What it the use of constant references in methods and functions? Is it a
design issue or hwat?

A reference that cannot be edited? huh?
Why pass a reference then?


At least one example of when constant references are useful is the case
when you want to pass an object as a read only parameter to some function:
class A
{
// add members here
}

void foo(const A& a)
{
// access a thru read only operations
}

By declaring the parameter 'a' as a const refernce you tell users of
foo() that their object won't be altered as a result of the call to
foo(). You also enable clever compilers to make assumptions on how 'a'
will be used inside foo() and based on that they might be able to do
some optimisations when compiling your code. Last but not least, if the
size of A should large you will avoid passing the whole object and
instead pass a suposedly much smaller reference.

:.:: mattias

Jul 22 '05 #3
On Tue, 25 Nov 2003 12:42:43 GMT, "Rickard Andersson"
<ri************@telia.com> wrote:
What it the use of constant references in methods and functions? Is it a
design issue or hwat?

A reference that cannot be edited? huh?
Why pass a reference then?


If you pass by value, a copy of the thing you are passing will be
made. Some objects either aren't copyable or are inefficient to copy,
so you pass them by const reference (or pointer). Finally, if you want
polymorphism, you have to use pass by reference otherwise you get
slicing. e.g.

void foo(const Base& b);

foo(aDerived);

Tom
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #4
Rickard Andersson wrote:
Okay, how do I know when I should pass a const reference and not a simple
const?

I guess you mean when you should one of the following

(1) void foo(const A& a);

(2) void foo(const A a);

My short answer to this would be: it makes little sense to do something
like (2). Since you are passing your A object by value the variable you
pass to foo() will be copied and there will be now way for foo() to
alter it. Declaring 'foo(const A a)' doesn't tell users of foo()
anything more than if you would declare it 'foo(A a)'.

:.:: mattias

PS. btw, you're swedish living in Luleå?

I'm swedish and living in Gothenburg. I used to study in Luleå.

Jul 22 '05 #5
Rickard Andersson wrote:
Okay, how do I know when I should pass a const reference and not a
simple const?


Well, a "simple const" as parameter isn't very useful. A function taking
an argument by value cannot modify that argument anyway, since the
function receives a copy. With some class types, a copy can easily get
quite expensive, and that's when you use call-by-reference instead of
call-by-value. And if the function doesn't modify the object, you use a
const reference. I think many people use call-by-value for builtin
small types and call-by-(const-)reference for most class types.
Jul 22 '05 #6

"Rickard Andersson" <ri************@telia.com> wrote in message
news:77********************@newsc.telia.net...
What it the use of constant references in methods and functions? Is it a
design issue or hwat?

A reference that cannot be edited? huh?
Why pass a reference then?


What is the alternative? Pass by value. When you pass by value, you make a
copy. If the object is tiny, it's no big deal. But some objects are not
tiny.
Jul 22 '05 #7
Mattias Brändström wrote:
Rickard Andersson wrote:
Okay, how do I know when I should [implement a function]
to pass a const reference and not a simple const?
I guess you mean when you should one of the following

(1) void foo(const A& a);

(2) void foo(const A a);


The second declaration is equivalent to

void foo(A a);

Identifier a is the *formal* argument.
When you invoke foo:

A a;
foo(a);

identifier a is the *actual* argument.
The compiler emits code to pass a by reference in the first case and
the compiler emits code to pass a by value in the second case.
It does *not* matter whether a is passed by value or const reference
as far as the program that invokes foo is concerned.
The only difference is that pass by reference doesn't require
the copy of the actual argument like pass by value.
This is an important optimization
only when a is larger than about one or two machine words.
My short answer to this would be:
it makes little sense to do something like (2).
Since you are passing your A object by value,
the [actual argument] you pass to foo() will be copied
[into the formal argument]
and there will be now way for foo() to alter [the actual argument].
Declaring 'foo(const A a)' doesn't tell users of foo()
anything more than if you would declare it 'foo(A a)'.


Using the const qualifier for formal arguments passed by value
is only useful in the function *definition*:

void foo(const A a) {
// The const qualifier informs the compiler that
// any attempt to modify a in the body of the function
// is a mistake and the compiler should issue a warning.
}

Jul 22 '05 #8

"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:3F**************@jpl.nasa.gov...

(1) void foo(const A& a);

(2) void foo(const A a);


The second declaration is equivalent to

void foo(A a);


Not really. If the definition is

void foo(const A a)
{
a = 3;
}

then there will be a compile error for (2).
Jul 22 '05 #9

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

Similar topics

6
1829
by: amparikh | last post by:
I know this is something fundamental and I ought to have known it, but somehow this seems to be confusing me a lot. Fundamentally, rvalues and/or temporaries can be bound only to constant references going by the const guidelines. Taking that into consideration, how does one get a constant reference to a pointer. class A
11
5257
by: lovecreatesbeauty | last post by:
Hello experts, Is const_cast only applied to pointers or references? If I have a constant object, then how can I remove constant attribute from it? #include <vector> #include <string> using namespace std;
22
2105
by: Ben Finney | last post by:
Howdy all, I've recently packaged 'enum' in PyPI. In its description, I make the claim that it creates "immutable" enumeration objects, and that the enumeration values are "constant" values. This raises questions. Is there any difference between a Python immutable value, and a constant? I suppose "constant" also implies that the *name*...
6
4883
by: cipher | last post by:
I have some constant values in my web service that my client application will require. Having to keep server side and client side definitions insync is tedious. I am trying to do something like this: public __value enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }; However, the resulting wsdl omits the actual flag values: -...
18
7312
by: William | last post by:
I have the following javascript function that updates a scroll_list and sends the updated entry (with its index) to a server script ( i.e. http://mkmxg00/cgi/confirmUpload.pl ) for further processing: function saveText( scroll_list, t_area, listToBeUpdated ) { scroll_list.options.text = t_area.text; scroll_list.options.value= t_area.value;...
13
27394
by: hn.ft.pris | last post by:
Hi: I have the following simple program: #include<iostream> using namespace std; int main(int argc, char* argv){ const double L = 1.234; const int T = static_cast<const int>(L); int arr;
13
1627
by: K. Jennings | last post by:
I have a function f with the following prototype: int f(void *). From my main() (or whatever) I can do things like int x = 123456 ; int y ; y = f(&x) ; which is fine. My question is, how can I pass the 123456 integer to f without using the intermediate x variable? Naively, what I would like to
12
1274
by: Bob Altman | last post by:
Hi all, I want to call a function that takes a void* argument and pass it the address of a constant. Is there a way to do this without explicitly defining the constant and then passing the address of the constant? In other words, what I *don't* want to do is this: const int myInt = 5; MyFunc(&myInt);
6
1767
by: Ruben | last post by:
re-reviewing the chapter in Lippan and Lajoie C++ Primer the have a section on references that I don't understand and just makes e shake my head believing that any behavior is possible with references and that they can never be understood. Maybe someone else can rephrase this so that I understand the defined behavior. cont int ival = 1024;...
0
7270
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...
0
7178
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...
0
7397
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. ...
1
7125
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...
0
5703
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...
1
5102
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...
0
1612
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
1
813
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
470
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...

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.