C++ – Use Cases for Non-Const Reference Parameters

ccoding-style

Given a function like:

void do_stuff( Thing & thing )
{
    // at this point, I can inadvertently or purposefully change thing
}

Is there a reason to purposefully change thing? Changing thing is possible but is it ill-advised?

Best Answer

Yes, so the function can change thing.

In general, it is best to put the behavior on the object itself. In other words, prefer this:

class Thing {
public:
  void do_stuff() {
    ...
  }
};

...to this:

void do_stuff( Thing & thing ) {
  ...
}

However, both examples are perfectly valid and usable. One good example of a non-member non-const reference parameter is stream extraction operators. This Stack Overflow question goes into more detail: Does anyone actually use stream extraction operators? The general idea is this:

operator>>(std::istream &, Thing &)

The function cannot exist as part of the Thing class because the left-hand is not an object of the class. It also needs to modify a Thing object so the reference cannot be const.

Related Topic