Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of "const -> std::string const&" after the function definition?

Tags:

c++

c++14

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?

like image 455
JP Zhang Avatar asked Aug 23 '16 15:08

JP Zhang


People also ask

What is const std :: string&?

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.

What does std :: string& mean in C++?

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.

How do you declare a string constant in C++?

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.

What is the difference between const char * and string?

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.


2 Answers

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).

like image 174
Bathsheba Avatar answered Sep 20 '22 18:09

Bathsheba


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; }
like image 28
R Sahu Avatar answered Sep 21 '22 18:09

R Sahu