error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘std::vector<bool>::reference {aka std::_Bit_reference}’

て烟熏妆下的殇ゞ 提交于 2019-11-28 03:43:00

问题


Why do I get the error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘std::vector::reference {aka std::_Bit_reference}’?

vector<vector<bool>> vis;
bool& visited(int x, int y)
{
    return vis[x][y]; //error
}

As far as I know operator[] in vector returns reference, so it should be an lvalue, but it doesn't work. What should I do to make it work?


回答1:


That's because std::vector< bool > is not what it looks like.

There's a specialization for std::vector with type bool - it's space optimized and uses a single bit for each element.

You can try to use uint8_t or something like this, if you need this functionality. Or just return bool, not bool&.

The reference, returned by operator[] is not a standard reference, but a proxy class, which complicates the things here.

There are a lot of similar questions about this here:

  • operator |= on std::vector<bool>
  • Why vector<bool>::reference doesn't return reference to bool?
  • Is the use of std::vector<bool> objects in C++ acceptable, or should I use an alternative?

And others. Read more about std::vector< bool > specialization.




回答2:


Normally, what you've assumed is the case, for literally any vector<T> except vector<bool>. The original C++98 standard specified that as a bit-packed vector, and so references to the individual elements are impossible.

This has since been recognized as an inconvenient mistake, but backward compatibility means that it can't be changed now.



来源:https://stackoverflow.com/questions/30376032/error-invalid-initialization-of-non-const-reference-of-type-bool-from-an-rva

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!