0

Tried to compile following code, can't understand error message.

#include<iostream>
#include<string>
using namespace std;
struct S {
    string a{"abc"};
    const string& data() { return a; }
};
int main() {
    S s;
    int a = s.data(); // error: no viable conversion from 'const std::string' to 'int'
    return 0;
}

Question: why does compiler say 'const std::string' instead of 'const std::string&'?

Tried with Apple clang 14.0.0 and g++ 12, same error message.

S55
  • 53
  • 5
  • Expressions in C++ never have a reference type. See dupe: [Does each expression in C++ have a non-reference type](https://stackoverflow.com/questions/67415226/does-each-expression-in-c-have-a-non-reference-type) – Jason Nov 03 '22 at 05:51

2 Answers2

5

data() returns a reference to a const std::string object, yes. But, you are not converting the reference itself to an int, you are converting the std::string object that it refers to.

A reference is just an alias, once a reference has been bound to an object, any access of the reference is really accessing the object instead.

That is why the error message does not include &.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
2

Expressions (such as s.data()) never have reference types.

& is silently removed from the type, and, in case of a function call, dictates the value category of the resulting expression (lvalue in this case).

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207