Search code examples
c++iteratorlvalue

Error: Initial value to non-const must be an lvalue


I'm getting a C2440 ('initializing' : cannot convert from 'std::_Vb_reference<_Alloc>' to 'bool &'), which IntelliSense translates to the error in the title.

I get what this error is saying, just not why it's being said. The code below produces this error:

std::vector<const UINT>::iterator oIter;

oIter = std::find(vecuClassID.begin(), vecuClassID.end(), uClassID);

const UINT uDistance = std::distance(vecuClassID.begin(), oIter);

bool& refbStaticSectionInitialized = *(vecbStaticSectionInitialized.begin() + uDistance);

The error seems to occur at the last line - in Visual Studio, the dereference operator is underlined in red. This is confusing because I have code that does the exact same thing with CRITICAL_SECTION, and that produces no error:

std::vector<const UINT>::iterator oIter;

oIter = std::find(vecuClassID.begin(), vecuClassID.end(), uClassID);

const UINT uDistance = std::distance(vecuClassID.begin(), oIter);

CRITICAL_SECTION& refhStaticSection = *(vechStaticSection.begin() + uDistance);

Does it have something to do with bool being a primitive?


Solution

  • The problem is that std::vector<bool> doesn't return bool& from its subscript operator or when dereferencing its iterator. Instead, the type returned is std::vector<bool>::reference which is a class not converting to bool&.

    The misguided idea behind std::vector<bool> is to adjust the interface to allow a packed representation. Since a bit isn't addressable, std::vector<bool>::reference works as a proxy for a bit.