invalid initialization of non-const reference when returning an array element

后端 未结 1 1915

I\'m writing a class that wraps a dynamically allocated array and I\'m trying to write the operator[] function. Currently I have:

bool& solution::operator[](         


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 18:47

    Its because the boolean literalfalse which is a rvalue, cannot be bound to non-const reference bool& which is the return type of operator[].

    Simply change the return type from bool& to bool, the error will disappear. But that isn't going to solve your problem, as you said,you want to return reference of the element, so that the element can be changed on the callsite, then you've to something like this:

    //correct solution
    bool& solution::operator[](unsigned int pos)
    {
      if(pos > _size)
         throw std::out_of_range("invalid index");
      return this->_data[pos];
    }
    

    That is, you should notify the caller of an invalid index, so that it can know that something went wrong. C++ various exception classes are there exactly for that purpose, i.e to notify error.

    Attempting to return any value (false or true) when the index is invalid, simply hides the problem. Ask yourself, if you return a dummy boolean value (which you store in the class), then would the caller know if the index was invalid? No.

    //incorrect solution
    bool& solution::operator[](unsigned int pos)
    {
      if(pos > _size)
         return _dummy; //it hides the problem, no matter if its true or false!
      return this->_data[pos];
    }
    

    0 讨论(0)
提交回复
热议问题