"error: passing 'const ***' as 'this' argument of '***' discards qualifiers [-fpermissive]" when using map::erase()

I'm implementing the following method to delete an element from an associative table (map):

1
2
3
4
5
6
7
8
9
10
//Method in gestion.cpp
void Gestion::EliminateObject(string nomobjetg) const{

    auto it = objectname.find(nameobjectg);

    if (it == objectname.end())
        cout << "Object not found!" << endl;
    else
        objectname.erase(it); //The error is reported in this line
}


In the header I have defined the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//gestion.h
#include "objects.h"
#include <list>
#include <iostream>
#include <string>
#include <memory>
#include <map>
using namespace std;

typedef std::shared_ptr<Objects> ObjPtr;

typedef map<string, ObjPtr> Objectmap;

class Gestion
{
private:
     Objectmap objectname;
     
public:
    Gestion(Objectmap objectname, Groupmap groupname);
    virtual ~Gestion() {}
    virtual void EliminateObject(string nameobjectg) const;
};


Where ObjPtr is a virtual pointer of objects of type Objects.

When I compile I get this error:

error: passing ‘const Objectmap {aka const std::map<std::basic_string<char>, std::shared_ptr<Objects> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::erase(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator) [with _Key = std::basic_string<char>; _Tp = std::shared_ptr<Objects>; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >]’ discards qualifiers [-fpermissive]
         objectname.erase(it);


Why is this line reporting this error?
Last edited on
You are trying to modify a non-mutable member in a method that is const.
@cire, is the iterator it non-mutable? as I understand, Objectmap is constant but I don't get how does that affect when I try to delete the iterator.
You don't delete iterators. The iterator refers to an element of objectname. You attempt to erase that element in objectname, but you cannot change objectname because the method enclosing this attempt to erase the element is const.
Topic archived. No new replies allowed.