如何从对象中清空std :: set'指针?

时间:2017-07-01 09:58:41

标签: c++ pointers memory-leaks stdset object-destruction

我有一个问题是清空我的设置,所以我有3个类似的那样:
A类和2个继承的B和C类。 在代码中我从3种类型中存储我的集合中的元素,该集合是:

set<A*> objects;

所以每当我创建一个B元素时,我都这样做:

A* b = new B(); // calling B C'tor 

// and so on with A and C elements I do the exact same.`

所以问题来了,每当我想要删除一个元素,或者甚至结束程序(调用析构函数)时,我都不知道我应该在析构函数中输入什么,我就是这样:

set<A*>::iterator first = objects.begin();
set<A*>::iterator last = objects.end();
while (first != last) {
    set<A*>::iterator to_delete = first;
    objects.erase(to_delete);
    delete *to_delete;    
    ++first;
}

我也尝试将delete *to_delete;放在objects.erase之上, 也尝试单独使用,并尝试在没有delete的情况下单独删除,但问题是我使用了new所以我应该在某处使用delete。 所有的东西都没有用,程序只是崩溃了,我试着把D&#39翻转为空,程序正常,但是我有很多内存泄漏,我已经检查了。

请帮助我,我坚持这件事。 非常感谢你&lt; 3

文件: 除了析构函数和removeRoom函数之外,一切都运行得很好(基本上是删除..运算符&lt;&lt;&lt; isn&#39; t正常工作但我相信它是因为那件事我再次virtual ~EscapeRoomWrapper();

#include <string>
#include <iostream>
#include <set>
#include "Company.h"
#include "ScaryRoom.h"
#include "KidsRoom.h"
#include "Exceptions.h"

using std::set;
using std::endl;

using namespace mtm;
using namespace escaperoom;

Company::Company(string name, string phoneNumber) : name(name), phoneNumber(phoneNumber) {

}

Company::~Company() {
    while(!rooms.empty()) {
        set<EscapeRoomWrapper*>::iterator iter = rooms.begin();
        rooms.erase(iter);
        delete *iter;
    }
//  set<EscapeRoomWrapper*>::iterator first = rooms.begin();
//  set<EscapeRoomWrapper*>::iterator last = rooms.end();
//  while (first != last) {
//      set<EscapeRoomWrapper*>::iterator to_delete = first;
//      rooms.erase(to_delete);
//      delete *to_delete;
//
//      ++first;
//      last = rooms.end();
//  }
//  while (rooms.begin() != rooms.end()) {
//      set<EscapeRoomWrapper*>::iterator to_delete = rooms.begin();
//      rooms.erase(to_delete);
//      delete *to_delete;
//  }
}

Company::Company(const Company& company) : name(company.name), phoneNumber(company.phoneNumber), rooms(company.rooms) {

}

Company& Company::operator=(const Company& company) {
    if (this == &company) {
        return *this;
    }
    name = company.name;
    phoneNumber = company.phoneNumber;
    rooms.clear();
    rooms = company.rooms;
    return *this;
}

void Company::createRoom(char* name, const int& escapeTime, const int& level, const int& maxParticipants) {
    try {
        EscapeRoomWrapper* room = new EscapeRoomWrapper(name, escapeTime, level, maxParticipants);
        rooms.insert(room);
    } catch (EscapeRoomMemoryProblemException& e) {
        throw CompanyMemoryProblemException();
    }
}

void Company::createScaryRoom(char* name, const int& escapeTime, const int& level,
                                 const int& maxParticipants, const int& ageLimit, const int& numOfScaryEnigmas) {
    try {
        EscapeRoomWrapper* room = new ScaryRoom(name, escapeTime, level, maxParticipants, ageLimit, numOfScaryEnigmas);
        rooms.insert(room);
    } catch (EscapeRoomMemoryProblemException& e) {
        throw CompanyMemoryProblemException();
    }
}

void Company::createKidsRoom(char* name, const int& escapeTime, const int& level,
        const int& maxParticipants, const int& ageLimit) {
    try {
        EscapeRoomWrapper* room = new KidsRoom(name, escapeTime, level, maxParticipants, ageLimit);
        rooms.insert(room);
    } catch (EscapeRoomMemoryProblemException& e) {
        throw CompanyMemoryProblemException();
    }
}

set<EscapeRoomWrapper*> Company::getAllRooms() const {
    return rooms;
}

void Company::removeRoom(const EscapeRoomWrapper& room) {
    set<EscapeRoomWrapper*>::iterator first = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last = rooms.end();
    while (first != last) {
        if (**first == room) {
            break;
        }
        ++first;
    }
    if (first == last) {
        throw CompanyRoomNotFoundException();
    }
    delete *first;
    rooms.erase(first);
   // delete *first;     // check this
}

void Company::addEnigma(const EscapeRoomWrapper& room, const Enigma& enigma) {
    set<EscapeRoomWrapper*>::iterator first = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last = rooms.end();
    while (first != last) {
        if (**first == room) {
            break;
        }
        ++first;
    }
    if (first == last) {
        throw CompanyRoomNotFoundException();
    }
    (**first).addEnigma(enigma);
}

void Company::removeEnigma(const EscapeRoomWrapper& room, const Enigma& enigma) {
    set<EscapeRoomWrapper*>::iterator first = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last = rooms.end();
    while (first != last) {
        if (**first == room) {
            break;
        }
        ++first;
    }
    if (first == last) {
        throw CompanyRoomNotFoundException();
    }
    try {
        (**first).removeEnigma(enigma);
    } catch (EscapeRoomNoEnigmasException& e) {
        throw CompanyRoomHasNoEnigmasException();
    } catch (EscapeRoomEnigmaNotFoundException& e) {
        throw CompanyRoomEnigmaNotFoundException();
    }
}

void Company::addItem(const EscapeRoomWrapper& room, const Enigma& enigma, const string& element) {
    set<EscapeRoomWrapper*>::iterator first_room = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last_room = rooms.end();
    while (first_room != last_room) {
        if (**first_room == room) {
            break;
        }
        ++first_room;
    }
    if (first_room == last_room) {
        throw CompanyRoomNotFoundException();
    }
    vector<Enigma>::iterator first = (**first_room).getAllEnigmas().begin();
    vector<Enigma>::iterator last = (**first_room).getAllEnigmas().end();
    while (first != last) {
        if (*first == enigma) {
            break;
        }
        ++first;
    }
    if (first == last) {
        throw CompanyRoomEnigmaNotFoundException();
    }
    (*first).addElement(element);
}

void Company::removeItem(const EscapeRoomWrapper& room, const Enigma& enigma, const string& element) {
    set<EscapeRoomWrapper*>::iterator first_room = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last_room = rooms.end();
    while (first_room != last_room) {
        if (**first_room == room) {
            break;
        }
        ++first_room;
    }
    if (first_room == last_room) {
        throw CompanyRoomNotFoundException();
    }
    vector<Enigma>::iterator first = (**first_room).getAllEnigmas().begin();
    vector<Enigma>::iterator last = (**first_room).getAllEnigmas().end();
    while (first != last) {
        if (*first == enigma) {
            break;
        }
        ++first;
    }
    if (first == last) {
        throw CompanyRoomEnigmaNotFoundException();
    }
    try {
        (*first).removeElement(element);
    } catch (EnigmaNoElementsException& e) {
        throw CompanyRoomEnigmaHasNoElementsException();
    } catch (EnigmaElementNotFoundException& e) {
        throw CompanyRoomEnigmaElementNotFoundException();
    }
}

set<EscapeRoomWrapper*> Company::getAllRoomsByType(RoomType type) const {
    set<EscapeRoomWrapper*> filtered_set;
    set<EscapeRoomWrapper*>::iterator first_room = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last_room = rooms.end();
    EscapeRoomWrapper* ptr = NULL;
    while (first_room != last_room) {
        if (type == BASE_ROOM) {
            if (dynamic_cast<ScaryRoom*>(*first_room) == ptr
                    && dynamic_cast<KidsRoom*>(*first_room) == ptr) {
                filtered_set.insert(*first_room);
            }
        }
        if (type == SCARY_ROOM) {
            if (dynamic_cast<ScaryRoom*>(*first_room) != ptr) {
                filtered_set.insert(*first_room);
            }
        }
        if (type == KIDS_ROOM) {
            if (dynamic_cast<KidsRoom*>(*first_room) != ptr) {
                filtered_set.insert(*first_room);
            }
        }
        ++first_room;
    }
    return filtered_set;
}

EscapeRoomWrapper* Company::getRoomByName(const string& name) const {
    set<EscapeRoomWrapper*>::iterator first_room = rooms.begin();
    set<EscapeRoomWrapper*>::iterator last_room = rooms.end();
    while (first_room != last_room) {
        if ((**first_room).getName() == name) {
            break;
        }
        ++first_room;
    }
    if (first_room == last_room) {
        throw CompanyRoomNotFoundException();
    }
    return *first_room;
}

std::ostream& mtm::escaperoom::operator<<(std::ostream& output, const Company& company) {
    output << company.name << " : " << company.phoneNumber << endl;
    set<EscapeRoomWrapper*>::iterator first_room = company.getAllRooms().begin();
    set<EscapeRoomWrapper*>::iterator last_room = company.getAllRooms().end();
    while (first_room != last_room) {
        output << **first_room << endl;
        ++first_room;
    }
    return output;
}

4 个答案:

答案 0 :(得分:1)

问题是objects.end()在从集合中移除某些内容时发生更改,并且last中存储的值无效。
您可以按如下方式修改代码:

    while (std::begin(objects) != std::end(objects)) {
        set<A*>::iterator to_delete = objects.begin();
        objects.erase(to_delete);
        delete *to_delete;
    }

通常,您不应该在集合中使用原始指针。而是使用像

这样的东西
std::set<std::unique_ptr<A>> objects;

在您的计划中。所以你根本不需要关心对象的正确释放。

答案 1 :(得分:1)

您的方法的关键问题是您在迭代容器时修改容器。我建议将其重构为:

while (!objects.empty()) {
     set<A*>::iterator it = objects.begin();
     objects.erase(it);
     delete *it;
}

或者你可以用C ++ 11和lamdas做这样的事情:

std::for_each(objects.begin(), objects.end(), [](A* obj){ delete obj; });
objects.clear();

<小时/> 刚刚根据您的描述对简化版本进行了测试,以下代码段非常适合我:

#include <iostream>
#include <set>

using namespace std;


class A {
};

class B : public A {
};

int main(int argc, const char *argv[])
{
    set<A*> objects;

    for (int i = 0; i < 10; i++) {
        objects.insert(new B());
    }

    for(set<A*>::iterator it = objects.begin(); it != objects.end(); ++it) {
        delete *it;
    }
    objects.clear();
    cout << "Hello World" << endl;
    return 0;
}

我怀疑我们在这里错过了一些细节。

<小时/> 更新

好的,虽然很难看到你在这里想要做什么的全貌,因为大多数细节仍然缺失,但我发现了复制构造函数的一个潜在问题。在您更新的代码中,您正在对公司对象进行浅层复制,但我认为您打算这样做:

Company& Company::operator=(const Company& company) {
    if (this == &company) {
        return *this;
    }
    name = company.name;
    phoneNumber = company.phoneNumber;
    // Also clear might be not enough since you also need to release heap memory

    //rooms.clear();

    while (!rooms.empty()) {
       set<A*>::iterator it = rooms.begin();
       rooms.erase(it);
       delete *it;
    }

    // Deep copy of set of rooms in company object
    for (set<Room*>::iterator it = company.rooms.begin(); it != company.rooms.end(); ++i ) {
       rooms.insert(new Room(*it));
    }
    return *this;
}

答案 2 :(得分:0)

如果您只想删除所有内容,那么这是一个更简单的解决方案。首先删除所有内容,然后调用clear()。您可以使用std::for_each将删除部分转换为单行。这是一个例子:

#include <algorithm>
// ...

std::for_each(begin(objects), end(objects), [](auto ptr) { delete ptr; });
objects.clear();

请注意,如果objects之后立即超出范围,则clear()甚至不需要。

如果你想删除一个元素,那么首先delete指针然后将其删除:

delete *iter; // decltype(iter) = std::set<A*>::iterator
objects.erase(iter);

还要考虑使用std::unique_ptr而不是原始指针。

答案 3 :(得分:0)

我相信你的问题是XY problem的一个例子:你想清空你的指针集,但你只想要那个,因为你想手动破坏那个集而不泄漏内存。而且你只需要这样做,因为自动销毁不会对你有所帮助。

我认为真正的解决方案是避免使用new进行手动分配。你会做什么呢?可能有3种选择:

  1. unique_ptr
  2. shared_ptr
  3. std::variant
  4. 我猜你真的不需要将一家公司分配给另一家公司而同时保留两家公司;因为您的赋值运算符和复制构造函数语义错误 :您正在通过另一家应该是const的公司来修改一个公司的房间。您可能只是执行move constructor

    Company::Company(Company&& company);
    

    您可以“抓住”旧公司的房间集,将其留空(可能是移动分配操作员)。如果是这种情况 - 您只有一个房间的引用,unique_ptr<EscapeRoomWrapper>会这样做。您不必手动删除任何内容,该集的默认析构函数也可以正常工作。实际上,您可能只能完全删除自定义移动构造函数,只使用默认值。

    如果需要多家公司引用同一个房间,并且确实需要那些非右值构造函数和赋值运算符 - 请使用shared_ptr<EscapeRoomWrapper>。同样,您不需要删除任何内容,并且在最后一次引用它们时将删除房间。这将花费你一些开销,但这不是性能关键代码,所以无关紧要。

    最后,如果房间种类有限,并且它们都从包装类继承 - 您可以考虑用不同房间类的std::variant替换虚拟继承,而不是使用指针 - 只是有一套房间。

    有关我的建议的其他灵感,请考虑阅读有关零的规则,例如:在this blog post

    PS - 您确定需要订购这套房间吗?如果不是,请使用std::unordered_set代替std::set