Search code examples
c++sfmlunique-ptr

Vector of unique pointers error, cannot be referenced after initialization


I'm trying to create a matrix of rectangles in SFML and have them look like a floor. To do that, I want to use a vector of unique pointers. However, there seems to be an error I don't quite understand.

After successfully initializing the vector, it is declared deleted in the very same function. When I do a similar implementation but using new or shared pointers, there are no problems.

What is causing this error, and how can I fix it? The place of occurance is visible below:

Code:

sf::Texture texture;

texture.loadFromFile("./resources/wood.jpg");

std::vector<std::unique_ptr<sf::Sprite>> floor;
unsigned counter = 0;
float posX = 0.f, posY = 0.f;
for (int i = 0; i < 50; i++) {
    floor.push_back(std::make_unique<sf::Sprite>());
    floor[i]->setTexture(texture);
    floor[i]->setTextureRect(sf::IntRect(1, 1, 100, 100));
    floor[i]->setPosition(sf::Vector2f(posX, posY));
    counter++;
    posX += 100.f;
    if (counter == 10) {
        posY += 100.f;
        posX = 0.f;
        counter = 0;
    }
}

while (window.isOpen()) {
    sf::Event eH;

    for (auto &sprite : floor)
        window.draw(*sprite.get());

    while (window.pollEvent(eH)) {
        if (eH.type == sf::Event::Closed)
            window.close();
        if (eH.type == sf::Event::KeyReleased && eH.key.code == sf::Keyboard::Escape)
            window.close();
        if (eH.type == sf::Event::Resized)
            glViewport(0, 0, eH.size.width, eH.size.height);
    }

    window.display();
    window.clear(sf::Color::Black);

Error description:

'std::unique_ptr<sf::Sprite,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function


Solution

  • This line

    for (auto sprite : floor)
    

    attempts to copy each unique_ptr into sprite one by one, and unique_ptrs aren't copyable.

    Use

    for (auto &sprite : floor)
    

    instead.