JP Zhang
JP Zhang

Reputation: 816

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

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?

Upvotes: 14

Views: 2322

Answers (4)

Surt
Surt

Reputation: 16099

It all makes more sense when you see an example where it actually matters; as written in the question, it's just an alternative way to declare the return type.

If you have a template function where you can not know the return type in advance, this can actually help. For example:

template <class X, class Y> auto DoSomeThing(X x, Y y) -> decltype(x * y);

You don't know what types X and Y actually are but you know the return value will have the same type as x * y which can be deduced in this way.

Upvotes: 4

Quentin
Quentin

Reputation: 63124

const is a cv-qualifier of the usual kind for the member function : *this is const inside the function.

-> std::string const& pairs with auto to form a trailing return type (see (2)). The difference is only syntactic here -- the following syntax is equivalent:

std::string const& get_name() const { return name; }

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234665

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

Upvotes: 21

R Sahu
R Sahu

Reputation: 206577

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; }

Upvotes: 9

Related Questions