tmatth
tmatth

Reputation: 499

Type of iterator for range-based for loop

Say I have the following code:

std::vector<std::string> foo({"alice", "bob"});
for (const std::string &f : foo)
    std::cout << f.size() << std::endl;

if I make a mistake and change f.size() to f->size(), I get the following error from GCC:

error: base operand of ‘->’ has non-pointer type ‘const string {aka const std::basic_string}

Why is the actual type const std::basic_string<char> rather than const std::basic_string<char> & (reference)?

Upvotes: 0

Views: 123

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

The left-hand side of -> operator is an expression. There ain't no such thing as an expression with a reference type:

5p5 If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

Upvotes: 1

Related Questions