Object cannot be assigned because its copy assignm

2019-07-10 07:09发布

问题:

In my small arkanoid clone game I'm trying to erase some values from a vector. This vector contains Brick classes, that are instantiated on the screen in a grid like pattern. When a collision happens between the ball and a brick, the brick needs to disappear. I'm trying to accomplish this with this small piece of code:

for (int i = 0; i < bricks.size(); ++i)
{
    if (bricks[i].destroyed)
    {
        bricks.erase(bricks.begin()+i);
    }
}

But unfortunately I get this compile error:

Object of type 'Brick' cannot be assigned because its copy assignment operator is implicitly deleted

When I click on this error it brings me to this piece of code:

for (; __first != __last; ++__first, (void) ++__result)
    *__result = _VSTD::move(*__first);
return __result;

Can somebody give me advice how to solve this?

回答1:

Can somebody give me advice how to solve this?

When you delete a non last element in a std::vector, it has to move all elements behind it. It can be done either by move-assignment (for C++11 or later) or copy assignment operator for an element. So to solve it, you either need to provide such operator for class Brick, use container that does not have to move elements like std::list or std::set etc or store smart pointers instead of objects themselv.



标签: c++ clang