2

A std::reference_wrapper is guaranteed to be initialized (but can be rebound, unlike a normal reference).

Being a wrapper class, what's the reason for std::reference_wrapper not to overload operator-> (and operator*)?

Instead, it is some other functions, like the get() method, to 'unwrap'.

I'm interested to hear what the deeper language reason is to why it is so (canonical or not).

11
  • 18
    Because it behaves like a reference, not like a pointer or iterator. Commented Jun 2 at 11:15
  • 4
    You can't do -> or * on a normal reference. Why would reference_wrapper allow it? Commented Jun 2 at 11:17
  • 1
    Any library developer should know when to stop adding functionality, specialy "utility functions". Any method added to an API has the risk of being misused (Hyrum's law). In this case reference wrapper has the API that lets it behave as much as possible as a reference any other functionality would be "utilitarian" and should not be added. Also the lack of -> and . it is an indication that reference wrapper should be used sparingly (since the reference wrapper is usually kind of used as a work-around) Commented Jun 2 at 11:35
  • 1
    Relevant Reddit discussion: reddit.com/r/cpp_questions/comments/1eu4b0y/… Commented Jun 2 at 11:38
  • 2
    I couldn't find any motivation in N1836 but adding operator-> and operator* was discussed at std-proposals last year. Commented Jun 2 at 16:00

1 Answer 1

3

std::reference_wrapper is designed to act like a C++ reference, not a pointer.

The operator-> is conventionally overloaded by types that behave like pointers (e.g., smart pointers such as std::unique_ptr or std::shared_ptr). Overloading operator-> for std::reference_wrapper would make it behave more like a pointer, which is not its intended semantic.

Sign up to request clarification or add additional context in comments.

2 Comments

Counter point: std::optional do have those operators and it is also not designed to act like a pointer per se.
This one is a interesting case. Although I could not find the exact reason for this, but I believe std::optional uses these operators because it deals with the potential presence of a value, similar to how a pointer might be "null" or point to a value. Whereas std::reference_wrapper aims to mimic a true reference as closely as possible, and true references use the dot (.) operator for member access. It must always refer to a valid object. It cannot be "empty" or "null" in the way std::optional can.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.