How was my operator overload working when I forgot to return *this

Started by
5 comments, last by rip-off 9 years, 4 months ago

Hi.

I have a class say

class foo

{

//assugnment operator =

const foo &foo::operator=(const foo &rhs)

{

check for self assignment

if(this == &s)

return *this;

//assign members

SomeFooValue = s. SomeFooValue;

Foostdvector = foostdvector;

//and here I forgot to return any thing

}

};

//that should be a error in vc10 c++ should it not

and how did it even work with out the return ;

I was using it and it was working fine ??????

Advertisement

Last I checked MSVC generates a warning for that. Apparently the standard does not require an error message. Still, you should get into the habit of checking (and resolving) warnings as well.

That said, it's undefined behavior. Sometimes it works. Sometimes it doesn't. Sometimes it works for weeks and suddenly break before an important release.


Sometimes it works for weeks and suddenly break before an important release.

biggrin.png

Some bugs have a mysterious way to sense release date and crash the software just before that.


Some bugs have a mysterious way to sense release date and crash the software just before that.

Schrodinger's bug.

I'd say you didn't use the operator overload in a chaining condition, so you didn't notice. The one path that does the object return must have fooled the compiler into thinking the definition was complete.

edit: +1 to Samith for having the same thought at the same time with example.

The operator itself has side effects (you're assigning SomeFooValue to s.SomeFooValue, for example), which occur even if you don't return a value. The return value from the = operator isn't used very often, and you probably wouldn't notice its absence unless you were chaining = operators together (for example: a = b = c; a is assigned the return value from the b = c operation). In regular use, a = b performs the = operator but the return value is discarded.

And, as others have said, usually the compiler will warn about a code path that doesn't return a value. You should make sure your warning levels are set high enough so that you don't end up returning nothing from a function by accident.

Try increase your compiler's warning level, if it isn't warning about such code. Also, try turning on the option that treats warnings as errors.

I know it isn't idiomatic, but sometimes I use a "void" return value from the assignment operator, as I rarely use chain assignment even with primitives, and never with more complex types.

This topic is closed to new replies.

Advertisement