Home > Net >  how to return a reference of an object from std::vector<std::vector<>>
how to return a reference of an object from std::vector<std::vector<>>

Time:08-01

like in the title, here is a pice of code:

class matrix{
    std::vector<std::vector<bool>> base;
    std::pair<int, int> size;
public:
    matrix(int x, int y){
        size.first = x; size.second = y;
        std::vector<std::vector<bool>> b(x, std::vector<bool>(y));
        base = b;
    }
    bool& operator ()(int x, int y) const {
        if(x < 0 || y < 0 || x >= size.first || y >= size.second){outOfBounds ex; throw ex;}
        return base[x][y];
    }
    /*and more that is unrelated to the question*/
};

the error is in bool& operator(...) and it is as follows:

cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type‘std::vector<bool>::const_reference’ {aka ‘bool’}
   30 |                 return base[x][y];

in the code, the size of the vector (matrix) dose not change

I also replaced bool with int and its the same problem, can't convert from int to int&

The function can't be const, so that the value of the reference can be changed

CodePudding user response:

bool& operator ()(int x, int y) const {

The const at the end means that this is a constant class method, and this is constant.

return base[x][y];

Everything in this is constant. Including this. The return value from this operator overload should, therefore, be const bool & instead of bool &.

If after understanding this you go back and reread your compiler's error message it should now make perfect sense to you, because that's exactly what your compiler was telling you.

Alternatively you can drop the const from the overloaded operator declaration, and return a bool &, that's up to you.

But then, you're going to wind up with another, special problem: a std::vector<bool> is not really a vector of bools, but something very weird.

So, the final solution may be to simply declare the return value as an auto &, and let the compiler figure it out for you. ...You don't really want to know what it really is.

  • Related