11

Let foo be a struct or class with a copy assignment operator:

struct foo {
    foo &operator=(const foo &);  // or with some other return type?
};

Is there ever a sensible reason to return anything other than *this from the operator=()? Using it for something unrelated to assignment doesn't qualify as sensible.

Sami Liedes
  • 1,084
  • 8
  • 19
  • 1
    When you return `this*`, you're making it possible for the assignment operator to be chained like `i = j = k = ...`. You can return other stuff, but how useful that is would be based on your definitions and how you want your classes to be used – Alex May 20 '15 at 21:38
  • 4
    Expression templates. – Alan Stokes May 20 '15 at 21:38
  • 5
    @AlanStokes It would be nice if you elaborated on that, you know. – Marius Bancila May 20 '15 at 21:44
  • interesting question, but why are you asking? Is it really a [practical, detailed question](http://stackoverflow.com/tour)? Then try to show it. – Wolf May 20 '15 at 21:45
  • 1
    note: the answers to the duplicate explore various scenarios where `*this` is not returned – M.M May 20 '15 at 22:49

2 Answers2

9

The example from the standard is std::atomic. It returns the assigned value. If it returned reference, then reading through it might yield different result.

zch
  • 14,931
  • 2
  • 41
  • 49
0

If you want to prevent assignment chaining.

Sometimes its nice to prevent expressions like this:

x = y = z = a = b = c = d = foo{15};

So you make the assignment operator return void.

struct foo {
    void operator=(const foo &);
};

For some types chaining does not make sense. But you have to look at that on a case be case basis.

Martin York
  • 257,169
  • 86
  • 333
  • 562