void operator=

P

Per

Hi!
I have a question about the operator=
I have seen two versions:

1.
void operator= (const SomeClass& C) {
....
}

2.
SomeClass& operator= (const SomeClass& C) {
....
return *this;
}

What is the difference and do one gain any performance using version
1. Is version 1 working with STL?
 
I

Ivan Vecerina

Per said:
Hi!
I have a question about the operator=
I have seen two versions:

1.
void operator= (const SomeClass& C) {
....
}

2.
SomeClass& operator= (const SomeClass& C) {
....
return *this;
}
This is the correct form, equivalent to the built-in versions
of the operator.
See "Effective C++" item 15.
What is the difference and do one gain any performance
using version 1.
A measurable gain is very unlikely, and it is even quite
possible that there would be no gain at all in code size
or execution speed.
Is version 1 working with STL?

It is not guaranteed to.
An STL implementation can legally assign objects as follows:
a = b = c;

hth,
Ivan
 
M

marieddu78

In the first case you can't do:
SomeClass a,b,c;
...
a=b=c;
In the second case you can!
 
R

Ron Natalie

Per said:
What is the difference and do one gain any performance using version
1. Is version 1 working with STL?

Both are legal and probably have the same performance.
The problem with #1 is that it does't emulate the builtin operator=
which is generally regarded as bad style.

SomeClass a, b, c;
a = b = c; // won't compile with a void returning op=
 
S

Swampmonster

Yeh, like the others already stated, the performance gain will be
minimal to non-existend - depending on the compiler and whether it
inlines the function or not.
Therefor no reason I can see not to return the ref.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,186
Messages
2,570,998
Members
47,587
Latest member
JohnetteTa

Latest Threads

Top