operator overloading q'n

R

rihad

Hi there. Suppose we have (in C):

if (x != y)
x = y;

it's obvious the conditional is unnecessary, and a C programmer would
frown upon this code most likely coming from a newbie who is somehow
convinced that the 'if' part makes his code faster by avoiding the more
"expensive" assignment. But this code *could* actually be faster in
C++, when dealing with classes and you never know what happens under the
hood (theoretically you *could* know this provided there's source code
and/or docs handy). How do you guys deal with this kind of stuff? Do the
authors of modern libraries avoid overloaded operators (even if they
make sense, like in std::string)? It's all to easy to forget that almost
any operator could actually be a function call, and the only way to keep
not forgetting it is to call the method explicitly (i.e. if
(foo.operator==(bar))). I could be wrong, please share your opinion ;)
 
J

Jeff Schwab

It's taken care of "under the hood," as you say. If the test for
equality is worthwhile, it will be done inside the assignment operator,
possibly circumventing the more expensive part of the assignment.

T const& T::eek:perator = ( T const& other )
{
if( *this != other )
{
// Do expensive copying and stuff.
}

return *this;
}
 

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,155
Messages
2,570,871
Members
47,401
Latest member
CliffGrime

Latest Threads

Top