尝试擦除unordered_map时双重释放或损坏

问题描述 投票:-2回答:1

我有一个继承自类案例的类Block:

class Case {
public:
    Case(sf::Vector2f const& pos, sf::IntRect const& textureRect, int type = 1);

protected:
    int type_;

    sf::Vector2f pos_;
    sf::FloatRect hitBox_;
    sf::IntRect textureRect_;
};

class Block : public Case {

public:
    Block(sf::Texture* const& texture, sf::Vector2f const& pos, sf::IntRect const& textureRect, int const& type = 2);

    sf::Sprite& getSprite();

private:
    std::shared_ptr<sf::Texture> texture_;
    sf::Sprite sprite_;

};

(两个构造函数都是基本的,我没有在任何地方使用任何新的)

我有一个unordered地图的无序地图来存储我的块:

std::unordered_map<int, std::unordered_map<int, Block>> blocks_;

但是当我尝试删除一个时:

if(blocks_[i%lenght].find((i-i%lenght)/lenght) != blocks_[i%lenght].end())
    blocks_[i%lenght].erase((i-i%lenght)/lenght);

我收到此错误:

double free or corruption (out)

我试图打印析构函数,在得到此错误之前,只调用了Block中的析构函数。

大约2个小时我正在寻找解决方案,所以我终于在这里问了,谢谢!

c++ sfml double-free
1个回答
3
投票

你的问题是构造函数:

Block::Block(sf::Texture *const &texture, sf::Vector2f const &pos,
             sf::IntRect const &textureRect, int const &type)
    : Case(pos, textureRect, 2), texture_(texture),
      sprite_(*texture_, textureRect_) {}

虽然以这种方式编写并不一定是错误的,但如果将相同的纹理传递给多个块则会出错:

sf::Texture *tex = new sf::Texture(/* ... params ... */);

Block b1(tex, /* ... remaining params ... */);
Block b2(tex, /* ... remaining params ... */);

现在两个单独的shared_ptr认为他们是tex的唯一所有者,所以只要其中一个块被删除,纹理也会被删除,所以如果两个块都被删除,那么你有一个双重免费。

因此,这被认为是反模式。通常,如果您使用智能指针,那么您应该看到原始指针不拥有指针,您永远不应该从不拥有指针构造智能指针。 (但是,这个规则有一个例外,如果您使用不使用智能指针的库,那么您需要检查它们返回或接收的原始指针是否被视为欠指针,如果是,它可能有效转换那个指向智能指针的原始指针。)

您的代码应该是这样的:

Block::Block(const std::shared_ptr<sf::Texture> &texture, sf::Vector2f const &pos,
             sf::IntRect const &textureRect, int const &type)
    : Case(pos, textureRect, 2), texture_(texture),
      sprite_(*texture_, textureRect_) {}

你应该像这样构建你的Blocks

std::shared_ptr<Texture> tex = std::make_shared<Texture>(/* ... params ... */);

Block b1(tex, /* ... remaining params ... */);
Block b2(tex, /* ... remaining params ... */);

这并不意味着你永远不应该使用原始指针。如果你是将有一个功能,将纹理绘制到屏幕,然后原始指针是完全正常的:

void draw_texture( sf::Texture * const tex) {
   // do some drawing but don't store tex somewhere
   // so tex is only used within that draw_texture call
}

然后你会这样称呼它:

std::shared_ptr<Texture> tex = std::make_shared<Texture>(/* ... params ... */);

draw_texture(tex.get());
© www.soinside.com 2019 - 2024. All rights reserved.