By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,227 Members | 1,290 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,227 IT Pros & Developers. It's quick & easy.

operator overloading q'n

P: n/a
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 ;)

Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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::operator = ( T const& other )
{
if( *this != other )
{
// Do expensive copying and stuff.
}

return *this;
}

rihad wrote:
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 ;)


Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.