vendredi 27 février 2015

Why does passing a vector of shared_ptrs by value to a lambda fail to compile? [duplicate]


This question already has an answer here:




To be specific, here's some code:



#include <memory>
#include <vector>

class Obj
{
public:
Obj(int number) : m_member(number) {}

int m_member;
};

int main(int argc, char *argv[])
{
std::vector<std::shared_ptr<Obj>> objPointers;

std::function<bool(int)> eventFunction = [=](int number)
{
auto objP = std::make_shared<Obj>(number);
objPointers.push_back(objP);
std::cout << number << " " << objP->m_member << std::endl;
return true;
};

eventFunction(20);

exit(EXIT_SUCCESS);
}


It fails to compile with this message: error: passing 'const std::vector<std::shared_ptr<Obj> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::shared_ptr<Obj>; _Alloc = std::allocator<std::shared_ptr<Obj> >; std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<Obj>]' discards qualifiers [-fpermissive]|


I don't understand why it believes that it's a const vector?


Aucun commentaire:

Enregistrer un commentaire