assignment operator

T

Tony Johansson

Hello!!

If I have part of the assignment operator below.
This statement check the addresses "if (this != &v)" and control so you
haven't assignt to your self.
Could I have checked the actual object like writing if (*this != v) will
that work?

const Array& Array::eek:perator=(const Array& v)
{
if (this != &v)
{
...
...
}
....
}

many thanks

//Tony
 
V

Victor Bazarov

Tony said:
If I have part of the assignment operator below.
This statement check the addresses "if (this != &v)" and control so you
haven't assignt to your self.

It's a good idea when dynamic memory is used.
Could I have checked the actual object like writing if (*this != v) will
that work?

That would invoke the operator !=. Have you defined it for your Array
class? What does it do? Do you really want to compare two arrays (no
one knows how huge they can be) before assigning? What if the difference
is in the very last element? You'll have spent much more time comparing
the arrays than you would simply assigning...
const Array& Array::eek:perator=(const Array& v)
{
if (this != &v)
{
...
...
}
...
}


V
 
A

Andre Kostur

Hello!!

If I have part of the assignment operator below.
This statement check the addresses "if (this != &v)" and control so you
haven't assignt to your self.
Could I have checked the actual object like writing if (*this != v) will
that work?

Maybe. Depends on what you actually want to accomplish. this != &v will
prevent an object from being assigned to itself. *this != v will prevent
an object from being assigned from another object with the same value (not
necessarily itself). As an example with ints:

int a = 5;
int b = 6;
int c = 5;

The first would detect a = a, but not a = c.

The second would detect both a = a, and a = c.



Now as Victor pointed out, is the cost of comparing your arrays to each
other more expensive than simply copying the array?
 

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

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top