Reading the answer for one exercise in C++ Primer, 5th Edition, I found this code:
#ifndef CP5_ex7_04_h
#define CP5_ex7_04_h
#include <string>
class Person {
std::string name;
std::string address;
public:
auto get_name() const -> std::string const& { return name; }
auto get_addr() const -> std::string const& { return address; }
};
#endif
What does
const -> std::string const&
mean in this case?
The data type const string& literally means “a reference to a string object whose contents will not be changed.” There are three ways to pass things around (into and out of functions) in C++: 1. Pass by value - a copy of the original object is created and passed.
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.
1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
auto get_name() const -> std::string const& { return name; }
is trailing return type notation for the equivalent
std::string const& get_name() const { return name; }
Note that the equivalence is exact in the sense that you can declare a function using one syntax and define it with the other.
(This has been part of the C++ standard since and including C++11).
The part -> std::string const&
is trailing return type and is new syntax since C++11.
The first const
says it a const
member function. It can be safely called on a const
object of type Person
.
The second part simply tells what the return type is - std:string const&
.
It is useful when the return type needs to be deduced from a template argument. For known return types, it is no more useful than than using:
std::string const& get_name() const { return name; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With