SunBathe
SunBathe

Reputation: 119

invalid initialization of non-const reference of type ‘std::string& from an rvalue of type ‘std::basic_string<char>

bool hasWord(int y, int x, string &word) {
    if(!inRange(y, x)) return false; 
    if(board[y][x] != word[0])  return false; 
    if(word.size() == 1) return true; 
    for(int direction = 0; direction < 8; direction++) {
        int nextX = x + dx[direction];
        int nextY = y + dy[direction];
        if(hasWord(nextY, nextX, word.substr(1)))  // <--- This
            return true;
    }
return false; }

error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘std::basic_string’ if(hasWord(nextY, nextX, word.substr(1)))

why the reason I was wrong?

Upvotes: 5

Views: 16047

Answers (3)

Arnab Das
Arnab Das

Reputation: 153

In case you wish to convert to non const reference of type std::string& from rvalue std::string, you could do something like:

auto stringRef = std::string(<string_value>);

and pass on the value.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

The reason of the error is that in this call

if(hasWord(nextY, nextX, word.substr(1))) 
                         ^^^^^^^^^^^^^^ 

there is created a temporary object of the type std::string and you are trying to bind a non-constant reference with the temporary object.

If the string is not changed in the function then just declare the function like

bool hasWord(int y, int x, const string &word) {
                           ^^^^^

Upvotes: 3

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

The error message says it all: invalid initialization of non-const reference of type std::string {aka std::basic_string} from an rvalue of type std::basic_string.

I.e. a reference to non-const cannot be bound to a temporary object (aka r-value). That temporary object is created by word.substr(1) expression.

In declaration:

bool hasWord(int y, int x, string &word)

Make it string const& word, since you do not need a modifiable word.

Upvotes: 8

Related Questions