473,803 Members | 2,038 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About const references

When you should not or can't use const references?

Like

void f ( const Foo& b) ;

or

int main() { const int& r = 5; }

Jan 27 '06 #1
2 1663

vineoff wrote:
When you should not or can't use const references?

Like

void f ( const Foo& b) ;
Use a const reference when you need access to data or query methods in
the object but won't be "changing" that object. By using a const
reference you are saying, "I am not going to change this object." Of
course you can violate that by const_cast and the object can have
"mutable" variables that can change in a const reference. It is a
contract that you make with clients of your class or method.

It also allows constant references to be passed in where otherwise they
can't. But this is really a concequence of the contract made by the
const keyword...you can't use anything on that object that could change
the object so you can't use non-const methods or pass it to a function
that would cause the constness of the object to go away.

or

int main() { const int& r = 5; }


That doesn't look legal.

Jan 27 '06 #2
vineoff wrote:
When you should not or can't use const references?
You should use references as arguments most of the time, unless there is
a compelling reason to use a pointer or pass by value.

You should use references as members when the lifetime of the owner of
that member does not exceed (ever) the lifetime of the referred object and
the association is never broken (or changed) during the lifetime of the
owner object. And of course, we assume no containment here, just the
association.

You should use references as return value types so that function calls
could be chained or the result could be used in an expression.

Now, as to 'const', you should always qualify your objects 'const' if you
don't expect to change them.

Now, combine the negative of those statements and you will get the reasons
_not_ to use references to const. For example, if in a situation calling
for *association* between objects you expect to break that association at
some moment during the lifetime of the *referring* object, then you should
not use a reference at all, and should use a pointer.
Like

void f ( const Foo& b) ;
This is a very common idiom.
or

int main() { const int& r = 5; }


This use of references while valid, is not warranted. You should simply
write

int main() { const int r = 5; }

V
--
Please remove capital As from my address when replying by mail
Jan 27 '06 #3

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

Similar topics

21
2133
by: JustSomeGuy | last post by:
When you iterate through a list of objects in a list. list<object> mylist; list<object>::const_iterator iter; object ob; for (iter=mylist.begin(); iter != mylist.end(); ++iter) { ob = *iter; ob.value = 10;
4
2849
by: cppsks | last post by:
I have been working on making a constant array available for the clients. However, it is placing it in the text segment, and external references result in unresolved references to the array. Taking the const off the definition solves the problem (the variable is placed in the data segment). Is this how const globals are supposed to work, or did the linker screw up? Thanks.
5
1538
by: Dave | last post by:
Hello all, I've been wondering... Why is it that a reference may be bound only to a const object? If a reference were bound to a non-const object and that object were modified, what harm could result? A temporary is just as real of an object as any other. It lacks a name, but that doesn't make it less real. Class (no pun intended) warfare seems to be alive and well! Thanks, Dave
75
5490
by: Steven T. Hatton | last post by:
No, this is not a troll, and I am not promoting Java, C-flat, D, APL, Bash, Mathematica, SML, or LISP. A college teacher recently posted to this newsgroup regarding her observation that there has been a significant decline in the number of students opting to take courses in C++. I just want to let people know what I believe are the biggest obstacles to C++ language acquisition, and what aspects of the language make it less appealing than...
21
1856
by: Bo Yang | last post by:
As long as I write c++ code, I am worry about the pointer. The more the system is, the dangerous the pointer is I think. I must pass pointers erverywhere, and is there a way to ensure that every object pointered by any pointer will be deleted and only be deleted once?
0
1285
by: Chris Thomasson | last post by:
I am fine-tuning some last minute things in my c++ allocator lib and was thinking of ways to manage local references to system objects created with factory functions. I started to tinker around with using const references to represent a smart-pointer template that uses intrusive reference counting. Anyway, here is a short little program that should clearly demonstrate what I am messing around with: _________________________ #include...
6
2355
by: Peter Lee | last post by:
what's the correct behaver about the following code ? ( C++ standard ) I got a very strange result.... class MyClass { public: MyClass(const char* p) { printf("ctor p=%s\n", p);
25
2097
by: raylopez99 | last post by:
First in an occasional series. I'm somewhat experienced in C++, and am using .NET Visual Studio 2005 as the IDE. I'm learning C#. What I don't like about C#, compared to C++ (all flavors): 1/ no pointers or tracking pointers or handles--this is absurd. I realise references are by and large like tracking pointers effectively (does anybody know of any differences--other than pointer arithmetic,
10
4026
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
9699
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
9562
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
10542
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10289
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,...
1
7600
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
6840
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();...
1
4274
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
2
3795
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2968
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.