The Case for Optional References--Tristan Brindle

And why not simply use a pointer?

The Case for Optional References

by Tristan Brindle

From the article:

I have a confession to make. Whenever I’ve come across code that looks like this:

struct example {
    example() = default;

    example(std::string& s) : str_{s} {}

private:
    boost::optional<std::string&> str_{};
};

there is a little voice inside my head that whispers “why didn’t you just use a pointer?”. Like so, for instance:

struct example {
    example() = default;

    example(std::string& s) : str_{&s} {}

private:
    std::string* str_ = nullptr;
};

This is equivalent to the first example, except that it’s slightly less typing, it doesn’t have any dependencies, and feels in some sense “cleaner”. I personally have always preferred it.

Except, I was wrong. After attending Bjarne Stroustrup’s keynote and this excellent talk at Cppcon this morning, I’m persuaded that optional references are a good thing. In this post I hope to be able to convince you of the same...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.