Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ref-qualified member functions

Use case

Different behavior for temporary vs persistent objects.

Explanation

& and && after member functions specify whether *this is an lvalue or rvalue. Return references from lvalues (persistent objects), move from rvalues (temporary objects).

Code

#include <iostream>
#include <vector>

class Buffer {
  std::vector<int> data_ = {1, 2, 3};

public:
  // lvalue.
  const std::vector<int> &data() const & {
    std::cout << "lvalue: returning ref.\n";
    return data_;
  }

  // rvalue.
  std::vector<int> data() && {
    std::cout << "rvalue: moving.\n";
    return std::move(data_);
  }
};

Buffer makeBuffer() { return Buffer{}; }

int main() {
  Buffer b;
  auto &ref = b.data();
  (void)ref;
  auto owned = makeBuffer().data();

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/ref-qualified-member-functions
lvalue: returning ref.
rvalue: moving.