2

I get an compile error here and I have no idea whats wrong with the code. I am using g++ 4.9.2.

#include<iostream>
#include<deque>

using std::string;
using std::deque;

class Dummy {
public:
    virtual ~Dummy(){};
    Dummy():ID_("00") {};
private:

    const string ID_;
};

int main(){
    {
    deque <Dummy> waiter;
    waiter.push_back(Dummy());
    waiter.erase( waiter.begin() );
    }
    return 0;
}

Edit: I know that removing the const removes the compilation error, but I have no idea why. Anyway, I need this const.

varantir
  • 6,624
  • 6
  • 36
  • 57

2 Answers2

5

std::deque::erase expects the type of element should be MoveAssignable:

Type requirements

T must meet the requirements of MoveAssignable.

And class Dummy has a const member const string ID_;, which make it not assignable by default assignment operator.

You might make ID_ a non-const member, or provide your own assignment operator to make it assignable. e.g.

Dummy& operator=(const Dummy&) { /* do nothing */ }

LIVE

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • That's the gist of it. Removing the erase also cures the compile error. – Component 10 Nov 24 '15 at 08:33
  • Agreed. I got the same result, but missed the relevance of the MoveAssignable requirement - well spotted! – Component 10 Nov 24 '15 at 09:13
  • @songyuanyao Do you think that your solution with making it "assignable" is legal? I think there must be a reason that it should be MoveAssignable ... – varantir Nov 24 '15 at 09:23
  • 1
    @varantir It's the requirment of the method. Image that if you erase an element in middle of the `deque`, it has to move the remaining elements to fill the vacancy. That means it will call assignment operator to move their position. – songyuanyao Nov 24 '15 at 09:32
  • @songyuanyao But If I modify the move assignable operator accordingly, I do not think the moving when erasing an element will work properly! – varantir Nov 24 '15 at 10:01
  • @varantir Not sure I understand you correctly...do you mean [this](http://ideone.com/ffiSEf)? – songyuanyao Nov 24 '15 at 10:21
0

you should remove the const prefix, so that the string can be changed:

string ID_;

or else change it to a static variable and initialize it like this:

class Dummy {
public:
    virtual ~Dummy(){};
    Dummy() {};
private:

    static const string ID_;
};

const string Dummy::ID_ = "00";

you can find more information here about const string initialisation.

Community
  • 1
  • 1
Chris Maes
  • 35,025
  • 12
  • 111
  • 136