**小心** ,这个程序不仅会挂起,而且显然会永远占用你的所有内存,让你的计算机变得缓慢而糟糕。我已经在很长一段时间里一直在努力解决这个问题,并且想出了很多东西 - 除了为什么它真的挂了。很抱歉,有这么多代码,但我删除了所有不相关的内容,这就是剩下的内容。
链表
//=====================
// Linked List
#include <stdexcept>
template<class T> struct LinkedList {
public:
LinkedList();
LinkedList(const LinkedList& srcList);
~LinkedList();
void addObject (T& addedObject);
class ListIterator {
public:
ListIterator();
explicit ListIterator(LinkedList<T>& parentList);
// Operators
ListIterator& operator++();
T& operator*() const;
bool operator!=(const ListIterator& otherIter);
private:
typename LinkedList::Node* current_;
};
ListIterator begin();
ListIterator end();
std::size_t size_;
private:
struct Node {
Node();
Node(T& object);
Node(const Node&) = delete;
T* const object_;
Node* next_;
Node* prev_;
};
Node head_;
Node tail_;
};
//====================
// Classes (Implementation)
// Linked List default constructor
template<class T> LinkedList<T>::LinkedList()
: size_{0} {
head_.next_ = &tail_;
tail_.prev_ = &head_;
};
// Linked List copy constructor
template<class T> LinkedList<T>::
LinkedList(const LinkedList& srcList) {
size_ = srcList.size_;
head_.next_ = &tail_;
tail_.prev_ = &head_;
ListIterator nodesToCopy = srcList.begin();
while (nodesToCopy != srcList.end()) {
this->addObject(*nodesToCopy);
srcList.removeObject(1);
};
delete &srcList;
};
// Linked List destructor
template<class T> LinkedList<T>::~LinkedList() {
for (unsigned int ii = 1; ii == size_; ++ii) {
Node* toDelete = head_.next_;
head_.next_ = head_.next_->next_;
delete toDelete;
};
};
// Add object to Linked List
template<class T> void LinkedList<T>::addObject(T& addedObject) {
Node* node = new Node(addedObject);
node->prev_ = tail_.prev_;
tail_.prev_->next_ = node;
tail_.prev_ = node;
node->next_ = &tail_;
++size_;
};
// Linked List Iterator constructor
template<class T> LinkedList<T>::ListIterator::
ListIterator(LinkedList<T>& parentList) {
current_ = parentList.head_.next_;
};
// Iterator operators
// Increment forward
template<class T> typename LinkedList<T>::ListIterator& LinkedList<T>::
ListIterator::operator++() {
current_ = current_->next_;
return *this;
};
// Return object pointed to
template<class T> T& LinkedList<T>::ListIterator::
operator*() const {
return *(current_->object_);
};
template<class T> bool LinkedList<T>::ListIterator::
operator!=(const ListIterator& otherIter) {
return &(**this) != &(*otherIter);
};
// Return an iterator object via begin() and end()
template<class T> typename LinkedList<T>::ListIterator
LinkedList<T>::begin() {
ListIterator beginIterator(*this);
return beginIterator;
};
template<class T> typename LinkedList<T>::ListIterator
LinkedList<T>::end() {
ListIterator endIterator(*this);
for (unsigned int ii = 0; ii < size_; ++ii) { ++endIterator; };
return endIterator;
};
// Node constructors
template<class T> LinkedList<T>::Node::Node()
: object_(nullptr), next_(nullptr), prev_(nullptr) {};
template<class T> LinkedList<T>::Node::Node(T& object)
: object_(&object) {};
物品
//=====================
// Item
//====================
// Included dependencies
#include <string>
#include <array>
#include <map>
#include <iostream>
class Item {
public:
Item();
Item(std::string name);
Item(std::string name, std::array<int, 2> stats);
std::map<std::string, int> getStats();
std::string name_;
private:
std::map<std::string, int> enhancements_;
};
// Constructors
Item::Item() {
enhancements_["Str"] = 0;
enhancements_["Def"] = 0;
};
Item::Item(std::string name) : Item::Item() { name_ = name; };
Item::Item(std::string name, std::array<int, 2> stats)
: Item::Item(name) {
enhancements_["Str"] = stats[0];
enhancements_["Def"] = stats[1];
};
// Return map of stats
std::map<std::string, int> Item::getStats() { return enhancements_; };
间
//====================
// Room
class Room {
public:
void addItem(Item item);
LinkedList<Item>::ListIterator getItems();
LinkedList<Item> itemsInThisRoom_;
};
// Add item to room
void Room::addItem(Item item) { itemsInThisRoom_.addObject(item); };
// Get iterator which iterates over items in room
LinkedList<Item>::ListIterator Room::getItems() {
return itemsInThisRoom_.begin();
};
主要
int main() {
std::array<int, 2> swordStats = {{5, 0}};
std::array<int, 2> shieldStats = {{0, 2}};
std::array<int, 2> armorStats = {{0, 3}};
Item sword("Sword", swordStats);
Item shield("Shield", shieldStats);
Item armor("Armor", armorStats);
Room room;
room.addItem(shield);
room.addItem(sword);
room.addItem(armor);
LinkedList<Item>::ListIterator roomItems = room.itemsInThisRoom_.begin();
while (roomItems != room.itemsInThisRoom_.end()) {
(*roomItems).getStats();
++roomItems;
};
return 0;
};
所有这些都可以放在一个文件中并进行编译(我按类将其拆分以使其更易于阅读)。这是 main 中的行,它挂起:
(*roomItems).getStats();
这让我相信我的解除引用运算符有问题,对吧?如果我们在Room类的之外创建迭代器,取消引用它,并以相同的方式 getStats - 一切正常。
......所以Room类的问题是什么?
但是,如果我们将 Item 和 main 更改为以下内容:
//=====================
// Item
//====================
// Included dependencies
#include <string>
#include <array>
#include <map>
#include <iostream>
class Item {
public:
Item();
Item(std::string name);
Item(std::string, int);
int getStats();
std::string name_;
private:
int enhancements_;
};
// Constructors
Item::Item() {
enhancements_ = 0;
};
Item::Item(std::string name) : Item::Item() { name_ = name; };
Item::Item(std::string name, int stats)
: Item::Item(name) {
enhancements_ = stats;
};
// Return map of stats
int Item::getStats() { return enhancements_; };
//====================
// Room
class Room {
public:
void addItem(Item item);
LinkedList<Item>::ListIterator getItems();
LinkedList<Item> itemsInThisRoom_;
};
// Add item to room
void Room::addItem(Item item) { itemsInThisRoom_.addObject(item); };
// Get iterator which iterates over items in room
LinkedList<Item>::ListIterator Room::getItems() {
return itemsInThisRoom_.begin();
};
int main() {
Item sword("Sword", 1);
Item shield("Shield", 2);
Item armor("Armor", 3);
Room room;
room.addItem(shield);
room.addItem(sword);
room.addItem(armor);
LinkedList<Item>::ListIterator roomItems = room.itemsInThisRoom_.begin();
while (roomItems != room.itemsInThisRoom_.end()) {
(*roomItems).getStats();
++roomItems;
};
return 0;
};
一切都运行得很好。我可以返回 int 值。
...所以......它既不是Room类或dereference运算符的问题,但返回 std :: map? GDB没有太多话要说。当我在违规线和步骤中突破时,我得到:
24 std::map<std::string, int> Item::getStats() { return enhancements_; };
(gdb) step
_Rb_tree_impl (__a=<optimized out>, __comp=..., this=0x7fffffffced0)
at /usr/include/c++/4.9/bits/stl_tree.h:474
474 _M_header(), _M_node_count(0)
(gdb) step
475 { _M_initialize(); }
(gdb) step
_M_initialize (this=0x7fffffffced0)
at /usr/include/c++/4.9/bits/stl_tree.h:484
484 this->_M_header._M_left = &this->_M_header;
(gdb) step
485 this->_M_header._M_right = &this->_M_header;
(gdb) step
_Rb_tree (__x=..., this=0x7fffffffced0)
at /usr/include/c++/4.9/bits/stl_tree.h:674
674 if (__x._M_root() != 0)
(gdb) step
_M_root (this=0x7fffffffd048)
at /usr/include/c++/4.9/bits/stl_tree.h:498
498 { return this->_M_impl._M_header._M_parent; }
(gdb) step
_Rb_tree (__x=..., this=0x7fffffffced0)
at /usr/include/c++/4.9/bits/stl_tree.h:674
674 if (__x._M_root() != 0)
(gdb) step
676 _M_root() = _M_copy(__x._M_begin(), _M_end());
(gdb) step
std::_Rb_tree<std::string, std::pair<std::string const, int>, std::_Select1st<std::pair<std::string const, int> >, std::less<std::string>, std::allocator<std::pair<std::string const, int> > >::_M_copy (
this=this@entry=0x7fffffffced0, __x=0x619f10,
__p=__p@entry=0x7fffffffced8)
at /usr/include/c++/4.9/bits/stl_tree.h:1207
1207 _Link_type __top = _M_clone_node(__x);
......这对我来说是胡言乱语。 :(它无限地执行此操作,因此我知道它(以某种方式)描述了挂断。
,我已经没有了解这里发生了什么,哈哈。我对C ++很陌生,自从我醒来以来就一直在努力解决这个问题,所以我知道我的代码很糟糕,我应该感觉不好写。
有什么想法吗?
答案 0 :(得分:6)
除了已经提到的内容之外,您的Node
对象不加掩饰地存储指针,该指针是通过引用从外部传递的对象
template<class T> LinkedList<T>::Node::Node(T& object)
: object_(&object) {};
但是,传递给Node
的构造函数的引用参数实际上绑定到局部变量
template<class T> void LinkedList<T>::addObject(T& addedObject) {
Node* node = new Node(addedObject);
node->prev_ = tail_.prev_;
tail_.prev_->next_ = node;
tail_.prev_ = node;
node->next_ = &tail_;
++size_;
};
void Room::addItem(Item item) { itemsInThisRoom_.addObject(item); };
即。引用绑定到参数item
,它是addItem
中的局部变量。
item
退出后,本地变量addItem
即被销毁。你的Node::object_
指针仍然没有指向。
考虑到您在代码中执行的无偿复制的数量,完全不清楚您是如何设法在Node
内存储指向非自有对象的指针(而不是无偿复制)将整个数据导入Node
,就像其他地方一样。)
无论如何,代码中的内存所有权完全被破坏,导致对象生命周期问题如上所述。您需要从头开始设计一些有意义的内存所有权计划,然后按照该计划编写代码。你现在拥有的是无法挽救的混乱。
如果你想使用指针并且你不认为你已经准备好解开这个混乱,只需使用智能指针让他们为你处理事情。
P.S。并放弃在每个;
之后放置}
的讨厌习惯。
答案 1 :(得分:1)
来自template<class T> LinkedList<T>::LinkedList(const LinkedList& srcList)
delete &srcList;
真的?只需删除此行即可改善您的代码。 &srcList
不一定是已在堆上分配的地址。无论如何,复制构造函数不应该删除原始文件。
来自template<class T> LinkedList<T>::~LinkedList()
for (unsigned int ii = 1; ii == size_; ++ii)
除非列表的大小为1,否则此循环无效,它应该是
for (unsigned int ii = 0; ii < size_; ++ii)