Stupid Reference Tricks, Part 2

The last post I wrote about C++ was about an unfortunately too-common programming practice of writing a class so that it provides a direct reference to an internal data-member. Here is the offending code, yet again:

class Widget {
private:
  double m_distance;

public:
  double & distance() { return m_distance; }
  const double & distance() const { return m_distance; }
};

I showed this kind of approach in my Advanced C++ track last night, and here is something that one of my students thought of: Can you grab a reference to Widget’s m_distance data-member, and hang on to it?

In other words, what does this code print:

  Widget w;
  w.distance() = 5;

  double &evil = w.distance();
  evil = -2;

  cout << w.distance();

Hopefully you are as horrified as I am… The variable evil is now a reference to an internal data-member of the Widget object, a data-member that is supposed to be private!!! This code actually prints out -2.

I don’t know why in the world people think this pattern is a good idea.

2 Responses to “Stupid Reference Tricks, Part 2”

  1. Ben Says:

    Where do people say this is a good pattern?

    I’m confused about the whole example. This doesn’t look like modern C++ code that anyone would be writing these days… well, at least, anyone who’s anyone. :)

  2. donnie Says:

    As you say, “no one who’s anyone” says that this is a good pattern. It’s clearly an anti-pattern. Nonetheless, I have come across people using it on large-scale C++ coding projects twice already here at Caltech, and I’ve only been here half as long as you were.

    There are standard C++ APIs that do this kind of thing, too. For example, if you look at the std::string at() function, it can also be used as the target of assignment. I think that what may happen is that people see this, and they think it’s a good approach in general. They don’t realize that providing a non-const reference to an internal data member is to be used very infrequently, and only in very particular situations.

    Anyway, by virtue of the simple fact that people are using it, somebody somewhere clearly thinks it’s a good idea. They just don’t realize that it completely violates encapsulation. If they did, hopefully they would stop using it.

    All I can do is push back the boundaries of ignorance one class at a time… ;-)

Leave a Reply