Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation failure associated with vector of const std::string

Please can someone explain why the following code doesn't compile using clang 3.5.

The error reported is 'No viable overloaded '=' in algorithm.'

std::vector<const std::string> m_messages;
std::vector<const std::string>::iterator iter;
...

if (iter != m_messages.end())
{
    m_messages.erase(iter);      // compilation error
}

If I declare m_messages as: std::vector<std::string> m_messages; then it compiles OK.

Also, what is the difference between:

std::vector<const std::string> m_messages;

and

std::vector<std::string> m_messages;

TIA.

like image 726
ksl Avatar asked Apr 27 '15 15:04

ksl


2 Answers

To erase an element, the right hand side elements have to be relocated (shifted to the left).

Since your strings are const, the old element cannot be overwritten (via the = operator) hence the error.

like image 191
Karoly Horvath Avatar answered Nov 08 '22 18:11

Karoly Horvath


Does that mean it makes no sense to have a vector of const strings if the elements can be removed? Yes at least what the standard says

23.3.7.5 vector modifiers [vector.modifiers]

iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last);

Effects: Invalidates iterators and references at or after the point of the erase.

Complexity: The destructor of T is called the number of times equal to the number of the elements erased, but the move assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.

Throws: Nothing unless an exception is thrown by the copy constructor, move constructor, assignment operator, or move assignment operator of T.

like image 5
Abhijit Avatar answered Nov 08 '22 19:11

Abhijit