c++ - 使用 unique_ptr 和继承时双重释放或损坏

标签 c++ inheritance memory-management unique-ptr

问题:

覆盖 unique_ptr 时因“双重释放或损坏”而崩溃

设置:

我正在开发一个日历应用程序。我正在使用具有类 sf::Drawable 的 SFML .
我有一个类DayView : public sf::Drawable和一类 WeekView : public sf::Drawable . 这两个类是显示日历内容的具体实现。一天一星期。
在类里面CalendarScene我想要一个指向当前实现的指针,只需单击一下即可替换它。
所以我将它们放入 unique_ptr<sf::Drawable> displayImpl 中在覆盖时自动删除它们。

现在我分配 displayImpl = unique_ptr<WeekView>(new WeekView(...))
如果我现在按下按钮重新分配 displayImpl = unique_ptr<DayView>(new DayView(...))应用程序在 virtual 的( WeekView )析构函数中崩溃带有消息 *** Error in '/home/XXX/workspaces/CDT/XXX/Debug/XXX': double free or corruption (out): 0x0000000000f9ed60 ***

我还有一个 shared_ptr<vector<shared_ptr<Calendar::Entry>>>作为 *View 中任一成员类。不知道这个有没有作用。

我的问题在哪里?

代码

/*
 * CalendarScene.h
 *
 *  Created on: 17. Nov. 2016
 *      Author: martin
 */

#ifndef SCENES_CALENDARSCENE_H_
#define SCENES_CALENDARSCENE_H_

#include "../Scene.h"
#include "../api/google/GoogleApi.h"
#include "../api/Calendar.h"
#include "../event/Event.h"
#include <vector>
#include <memory>

class CalendarScene: public Scene {
    public:
        CalendarScene(GoogleApi * api);
        virtual ~CalendarScene();

        void prepare(const sf::Vector2u size) override;
        void event(Event &evt) override;

    private:
        void draw(sf::RenderTarget &, sf::RenderStates) const override;
        sf::String texttodisplay;

        std::vector<std::shared_ptr<Calendar>> calendars;
        Calendar::Entries ents;
        Json::Value calendarList;
        Json::Value eventList;

        enum { WEEK, DAY } displayMode;
        int wOffset;

        std::unique_ptr<sf::Drawable> displayImpl = nullptr;

};

#endif /* SCENES_CALENDARSCENE_H_ */

/*
 * CalendarScene.cpp
 *
 *  Created on: 17. Nov. 2016
 *      Author: martin
 */

#include "CalendarScene.h"
#include <SFML/Graphics.hpp>
#include <algorithm>
#include "../ui/SmartText.h"
#include "../ui/UIFactory.h"
#include "../util/sfmladditions.h"

using std::unique_ptr;
using std::shared_ptr;
using std::runtime_error;
using std::time;
using std::time_t;
using std::string;

using io::curl::parameter_map;

using Json::Value;
using Json::ValueIterator;

namespace {

typedef shared_ptr<vector<shared_ptr<Calendar::Entry>>> SharedEntrySharedVector;

enum Format {
    PORTRAIT, LANDSCAPE
};


class WeekView : public sf::Drawable {
public:
    WeekView(SharedEntrySharedVector weekEntries) : ents(weekEntries) {}
    virtual ~WeekView() {}
protected:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
    SharedEntrySharedVector ents;
};

class DayView : public sf::Drawable {
public:
    int dayOffsetToNow = 0;

    DayView(SharedEntrySharedVector dayEnt) : ents(dayEnt) {}

protected:
    virtual void draw(sf::RenderTarget& target, sf::RenderStates) const;
private:
    SharedEntrySharedVector ents;
};

void WeekView::draw(sf::RenderTarget& target, sf::RenderStates) const {
    /* some drawing */
}

void DayView::draw(sf::RenderTarget& target, sf::RenderStates) const {
    /* some other drawing */
}

} // namespace

CalendarScene::CalendarScene(GoogleApi * api) :
        Scene(api), displayMode(WEEK), wOffset(0), displayImpl(new WeekView(SharedEntrySharedVector())) {
}

CalendarScene::~CalendarScene() {
    calendars.clear();
}

/*
 *
 * Obtain calendar list
 * Obtain event list
 *
 */
#include <iostream>
void CalendarScene::prepare(const sf::Vector2u target) {

    /* populating the ents.entries field which is of type vector<shared_ptr<Calendar::Entry>> */

    displayImpl = unique_ptr<WeekView>(new WeekView(SharedEntrySharedVector(&(ents.entries))));
}

void CalendarScene::event(Event &evt) {
    if (evt.type() == Event::Type::ScreenEvent) {
        /* nothing interesting */
    } else if (evt.type() == Event::Type::ButtonEvent) {
        ButtonEvent &b = (ButtonEvent&) evt;
        switch (b.eventChar()) {
        case sf::Keyboard::Key::W:
            displayMode = WEEK;
            displayImpl = unique_ptr<WeekView>(new WeekView(SharedEntrySharedVector(&(ents.entries))));
            break;
        case sf::Keyboard::Key::T:
            displayMode = DAY;
/********  Here lies the problem  ********/
            displayImpl = unique_ptr<DayView>(new DayView(SharedEntrySharedVector(&(ents.entries))));
            break;
        case sf::Keyboard::Key::Right:
            wOffset++;
            break;
        case sf::Keyboard::Key::Left:
            wOffset--;
            break;
        default:
            return;
        }
        if (wOffset < 0)
            wOffset = 0;
        else if (wOffset > 6)
            wOffset = 6;
        if (displayMode == DAY) {
            ((DayView*)displayImpl.get())->dayOffsetToNow = wOffset;
        }
    }
}

void CalendarScene::draw(sf::RenderTarget &target, sf::RenderStates) const {
    if (!displayImpl)
        return;

    target.draw(*displayImpl);
}

Valgrind 说:

==27630== Invalid free() / delete / delete[] / realloc()
==27630==    at 0x4C2A360: operator delete(void*)
==27630==    by 0x4B6D4D: std::_Sp_counted_ptr<std::vector<std::shared_ptr<Calendar::Entry>, std::allocator<std::shared_ptr<Calendar::Entry> > >*, (__gnu_cxx::_Lock_policy)2>::_M_dispose()
==27630==    by 0x411665: std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release()
==27630==    by 0x41054A: std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count() 
==27630==    by 0x4ABDC9: std::__shared_ptr<std::vector<std::shared_ptr<Calendar::Entry>, std::allocator<std::shared_ptr<Calendar::Entry> > >, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr() 
==27630==    by 0x4ABE51: std::shared_ptr<std::vector<std::shared_ptr<Calendar::Entry>, std::allocator<std::shared_ptr<Calendar::Entry> > > >::~shared_ptr()
==27630==    by 0x4A461E: (anonymous namespace)::WeekView::~WeekView() 
==27630==    by 0x4A46B3: (anonymous namespace)::WeekView::~WeekView() 
==27630==    by 0x4AE161: std::default_delete<sf::Drawable>::operator()(sf::Drawable*) const 
==27630==    by 0x4AF7BD: std::unique_ptr<sf::Drawable, std::default_delete<sf::Drawable> >::reset(sf::Drawable*)
==27630==    by 0x4AB181: std::enable_if<std::__and_<std::is_convertible<std::unique_ptr<(anonymous namespace)::DayView, std::default_delete<(anonymous namespace)::DayView> >::pointer, sf::Drawable*>, std::__not_<std::is_array<(anonymous namespace)::DayView> > >::value, std::unique_ptr<sf::Drawable, std::default_delete<sf::Drawable> >&>::type std::unique_ptr<sf::Drawable, std::default_delete<sf::Drawable> >::operator=<(anonymous namespace)::DayView, std::default_delete<(anonymous namespace)::DayView> >(std::unique_ptr<(anonymous namespace)::DayView, std::default_delete<(anonymous namespace)::DayView> >&&) 
==27630==    by 0x4AA445: CalendarScene::event(Event&) 
==27630==    by 0x4DC982: ClientWatch::ClientWatchPrivate::runWindowed() 
==27630==    by 0x4DC6AE: ClientWatch::ClientWatchPrivate::run() 
==27630==    by 0x4DC758: ClientWatch::run()
==27630==    by 0x529CE7: main 
==27630==  Address 0xeb334b0 is 48 bytes inside a block of size 176 alloc'd
==27630==    at 0x4C29180: operator new(unsigned long) 
==27630==    by 0x4E0904: _ZN11ClientWatch18ClientWatchPrivate9makeSceneI13CalendarSceneIRP9GoogleApiEEESt10unique_ptrI5SceneSt14default_deleteIS7_EEDpOT0_ 
==27630==    by 0x4DF88E: _ZN11ClientWatch18ClientWatchPrivate8newSceneI13CalendarSceneIRP9GoogleApiEEEvDpOT0_ 
==27630==    by 0x4DD519: ClientWatch::ClientWatchPrivate::drawFrame() 
==27630==    by 0x4DCB36: ClientWatch::ClientWatchPrivate::runWindowed() 
==27630==    by 0x4DC6AE: ClientWatch::ClientWatchPrivate::run() 
==27630==    by 0x4DC758: ClientWatch::run() 
==27630==    by 0x529CE7: main 
==27630== 

改变 unique_ptr s 至 shared那些没有帮助。仍然是 double free 错误。

最佳答案

我相信您可能正在复制此对象并将其删除到其他地方。 std::unique_ptr<> 应该能够处理您提到的情况。以此为例,它工作正常:

#include <memory>
#include <iostream>

struct A {
    int a;
    A( int v ) : a(v) {}
};

int main() {
    std::unique_ptr<A> p( new A(1) );
    p = std::unique_ptr<A>( new A(3) );
    std::cout << "A:" << p->a << "\n";
    return 0;
}

然后运行

$ clang++ -std=c++11 testUniquePtr.cpp -o testUniquePtr
$ ./testUniquePtr 
A:3

但是,如果您将指针分配给另一个 unique_ptr,例如

int main() {
    std::unique_ptr<A> p( new A(1) );
    std::unique_ptr<A> q( p.get() );
    std::cout << "A:" << p->a << "\n";
    return 0;
}

然后你得到双倍免费:

$ ./testUniquePtr 
A:1
*** Error in `./testUniquePtr': double free or corruption (fasttop): 
0x0000000001258c20 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f1ce28367e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x7fe0a)[0x7f1ce283ee0a]

关于c++ - 使用 unique_ptr 和继承时双重释放或损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090597/

相关文章:

python - 操作来自namedtuple()派生类的属性

c++ - 在动态分配的对象上调用 delete 是否总是内存泄漏?

c++ - MSXML 方法是否获取其 BSTR 参数的内存所有权?

c++ - boost iostreams 可以即时读取和压缩 gzip 文件吗?

c++ - 获取内联定义的友元函数的地址

c++ - 如何在 C 中打印没有空格的 NUL 字符?

c - 一旦超出范围,C 是否会重用本地 block var 的内存?

c++ - 如何区分(重载时)operator++ 的前缀和后缀形式? (C++)

c++ - 将对象指针转换为 char 数组

C++:将我的对象转换为不同的父类(super class)会导致不同的指针地址