core/personthis.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <string>

class Person {
private:
  std::string name;
public:
  Person (const std::string& n)
   : name{n} {
  }
  //...

  decltype(auto) getName(this auto&& self) {
    return std::forward<decltype(self)>(self).name;
  }
};


Person getPerson()
{
  return Person("TemporaryPerson");
}

int main()
{
  Person p{"Kim"};
  const Person cp{"Maria"};

  std::cout << p.getName() << '\n';   // fast
  std::cout << cp.getName() << '\n';  // fast

  //p.getName() = "Tim"; // ERROR
  //cp.getName() = "Mel"; // ERROR

  const auto& n = getPerson().getName();   // safe
  std::cout << n << '\n';                  // OK
}