//******************************************************** // The following code example is taken from the book // C++23 - The Complete Guide // by Nicolai M. Josuttis (www.josuttis.com) // http://www.cppstd23.com // // The code is licensed under a // Creative Commons Attribution 4.0 International License // http://creativecommons.org/licenses/by/4.0/ //******************************************************** #include #include class Person { private: std::string name; public: Person (const std::string& n) : name{n} { } //... decltype(auto) getName(this auto&& self) { return std::forward(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 }