Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

c++11

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?

like image 919
SunBathe Avatar asked Jan 03 '23 05:01

SunBathe


2 Answers

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.

like image 109
Maxim Egorushkin Avatar answered Feb 07 '23 12:02

Maxim Egorushkin


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) {
                           ^^^^^
like image 45
Vlad from Moscow Avatar answered Feb 07 '23 10:02

Vlad from Moscow