c++pass-by-const-reference

How do I safely hold on to a C++ const reference?


aka. how do I prevent a const& parameter from accidentally binding to a temporary?

We have a class that essentially looks like this:

template<typename T>
struct Observer {
  const T* target;

  void observe(const T& x) {
     target = &x;
  }
};

That is, these objects will "hold on" to the const-ref they get passed.

We had a bug where the observe function accidentally got passed a temporary object - something that can never be valid for this case.

What options do we have to prevent accidentally binding to a temporary?

Changing the signature to (const T* px) would work technically (taking the address of a temporary is a compiler warning=error here) it is not very attractive for other reasons.

Side note: Yeah, this will always have potential lifetime management issues, but so far the real thing worked pretty well because of its limited usage pattern - but passing temporaries accidentally has been observed in practice, so we want to possibly address that first.


Solution

  • You can add a rvalue reference overload, and delete it:

    void observe(const T&& x) = delete;
    

    Now a compile error will be issued if someone tries to pass a temporary.