-1

If I define operator+ for a type, in the usual fashion

struct S {};

S operator+(S const &, S const &) { 
  return {}; 
}

users of S can write code like

S s{};
s + s = S{}; // huh

From what I can tell, operator+ returns a temporary object of type S, which is then assigned to. The object then dies at the end of the statement, because there's no name for it, and so the statement is effectively a no-op.

I don't see any use for code like that, so I would like to make that a compile error. Is there a way to do that? Even a warning would be better than nothing.

cigien
  • 57,834
  • 11
  • 73
  • 112

2 Answers2

1

One simple way to prevent this from happening is to return a constant object:

const S operator+(S const &, S const &) { 
    return {}; 
}

That will now result in a compilation error, in this situation, but

s= s + s;

will still work just fine.

This, of course, has a few other ramifications, and may or may not have undesirable side-effects, which may or may not pose an issue, but that would be a new question, here...

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

Just found what I need here. Apparently I can make the assignment operator only bind to lvalues.

struct S {
    S& operator=(S const&) & // only binds to lvalues
    { 
      return *this; 
    }
}; 

Now I get exactly the error I want.

cigien
  • 57,834
  • 11
  • 73
  • 112