473,725 Members | 2,032 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

operator= with non-const reference parameter

Hello !

I've read in a magazine "reference parameter in operator= must be const,
because in C++, temporary objects are const" and then my operator would
not work with temporary objets.

But, my compiler doesn't have temporary const objects. Are there any
reasons to have a const reference parameter ?

Thanks in advance for your help

ded'
Jul 22 '05 #1
3 1967

"ded'" <de*@laposte.no spam.net> wrote in message
news:40******** *******@laposte .nospam.net...
Hello !

I've read in a magazine "reference parameter in operator= must be const,
because in C++, temporary objects are const"
Both half's of that statement are wrong. What was the magazine?

The rule that the magazine was probably trying to express is, temporary
objects cannot be bound to a non-const reference.
and then my operator would
not work with temporary objets.
That's correct.

But, my compiler doesn't have temporary const objects. Are there any
reasons to have a const reference parameter ?


Your thinking is wrong. The question you should ask is 'does my assignment
operator modify the value on the right hand side?' If the answer is no
(which it will be 99.9% of the time) then you should use a const reference.
It's all about better expressing the meaning of your code, not about 'does
it work with this compiler', or 'do I need to do it'.

Same goes for any other function you write, if it takes a reference
parameter and the reference is not used to modify the object then use a
const reference.

john
Jul 22 '05 #2
On Sat, 01 May 2004 18:11:49 +0200, ded' <de*@laposte.no spam.net> wrote:
Hello !

I've read in a magazine "reference parameter in operator= must be const,
because in C++, temporary objects are const" and then my operator would
not work with temporary objets.
Well, sometimes it matters and sometimes it doesn't. Let's say you simply
define operator= as taking a T& as in the following test program:

#include <iostream>
using namespace std;

class T
{
public:
T();
T &operator=(T &) { cout << "In T::operator=(T& )\n";
return *this; }
};

int main()
{
T t;
T t2;
t2 = t;
return 0;
}

It compiles and runs. So obviously either the magazine was wrong or you
misinterpreted what it said. I suspect it is the latter. The cases when
references must be declared const are when you bind them to constant
expressions, such as:
int const &ri = 10;

or:

void f(int &ri) {...}
...
f(10);

But, my compiler doesn't have temporary const objects.
I suspect it does.
Are there any
reasons to have a const reference parameter ?
The usual reason to show a ptr or ref parameter to /any/ function as ptr-to
-const or ref-to-const is for the benefit of "const correctness": to
"document" to the caller of the function that the argument in question will
not be modified. A reference-to-const or pointer-to-const parameter also
makes it possible for the argument passed in that position to actually have
a ptr-to-const or reference-to-const type. If we modify the definition of
t in main() above to be as follows:
const T t;
then the program will no longer compile. But changing the def of operator=
to:
T &operator=(cons t T &) { cout << "In T::operator=(co nst T&)\n";
return *this; }
works in all cases, supports const correctness and allows const right-hand
expressions when using operator=. What's not to like?
-leor
..


Thanks in advance for your help

ded'


--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Jul 22 '05 #3
ded' wrote:
I've read in a magazine "reference parameter in operator= must be const,
because in C++, temporary objects are const" and then my operator would
not work with temporary objets.
That's badly phrased. Sometimes it's reasonable to have a non-const
reference parameter to 'operator =', but it's true that in that case you
wouldn't be able to assign from a temporary. This isn't because
"temporary objects are const", it's because temporaries cannot be bound
to non-const references.
But, my compiler doesn't have temporary const objects.
What? Does it accept the following program?

int f () { return 0; }
void g (int & x) { ++ x; }
int main () { g (f ()); }

If so, ditch it and get a better one. Some of the best are free.
Are there any reasons to have a const reference parameter ?


Yes. The parameter should be a non-const reference if the function
modifies its argument and a const reference (or a value) otherwise.

--
Regards,
Buster.
Jul 22 '05 #4

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

Similar topics

11
912
by: Jonan | last post by:
Hello, For several reasons I want to replace the built-in memory management with some custom built. The mem management itlsef is not subject to my question - it's ok to the point that I have nice and working allocation deallocation routines. However, I don't want to loose the nice extras of new operator, like - constructor calling, typecasting the result, keeping the array size, etc. For another bunch of reasons, outside this scope I...
7
1831
by: Eckhard Lehmann | last post by:
Hi, I try to recall some C++ currently. Therefore I read the "Standard C++ Bible" by C. Walnum, A. Stevens and - of course there are chapters about operator overloading. Now I have a class xydata with operator- overloaded: class xydata { public:
17
2509
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: public static bool operator !=(MyType x, MyType y) { return !(x == y); } That way the == operator handles everything, and extra comparing logic isn't
5
8424
by: Dave | last post by:
I am a VB programmer tring to learn C# I am stuck on a bit operator "&" in VB: ' checkLogin = 3 means "Login exists" and "Employee Number exists" If (checkLogin And 1) Then lbError.Text = "Login already exists" End If If (checkLogin And 2) And txtEmpNum.Text <> 0 Then
6
1819
by: ghager | last post by:
Hi all, I must be blind or stupid. Please consider the following code: ---- .... template <class T> class P; template <class T> P<T> operator*(T,const P<T>&); template <class T>
7
6686
by: Alex Vinokur | last post by:
What is the difference between an operator and a function in C++? Alex Vinokur email: alex DOT vinokur AT gmail DOT com http://mathforum.org/library/view/10978.html http://sourceforge.net/users/alexvn
14
2806
by: Jess | last post by:
Hi, I read about operator overloading and have a question regarding "operator->()". If I have two classes like this: struct A{ void f(); }; struct B{
4
1780
by: aaragon | last post by:
Hi everyone, I was unable to find out why my code is not compiling. I have a template class and I'm trying to write the operator<< for standard output. Does anyone know why this is not right? The code is as follows... // main class: template < class Individual,
18
3230
by: Ranganath | last post by:
Why is throw keyword considered as an operator?
1
1282
by: subramanian100in | last post by:
Consider the following program: #include <iostream> #include <cstdlib> using namespace std; class Test { public:
0
8888
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
8752
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
9401
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...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9174
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,...
0
9111
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
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...
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.