初始化指向类实例的智能指针并访问其方法

Initializing a smart pointer to an instance of class and accessing its methods

本文关键字:指针 访问 方法 智能 实例 初始化      更新时间:2023-10-16

所以,我正在尝试使用排序列表实现优先级队列。我的优先级队列类继承自排序列表类。当我在驱动程序中测试其功能时,我的排序列表类工作正常,但是当我尝试测试优先级队列的实现时,我遇到了"Segmentation Fault 11"。我通过 CLion 调试器运行我的代码并得到错误"EXC_BAD_ACCESS (code=1, address=0x0)",经过一些研究,这似乎是由于尝试修改空指针中的数据引起的。这是我第一次使用智能指针,所以我认为我的问题在于对它们的构造和初始化方式的误解。

这是我的SL_PriorityQueue类的头文件:

#ifndef PRIORITY_QUEUE_
#define PRIORITY_QUEUE_
#include "PriorityQueueInterface.h"
#include "LinkedSortedList.h"
#include "PrecondViolatedExcep.h"
#include <memory>
template<class ItemType>
class SL_PriorityQueue : public PriorityQueueInterface<ItemType>
{
private:
std::unique_ptr<LinkedSortedList<ItemType> > slistPtr;
public:
SL_PriorityQueue();
SL_PriorityQueue(const SL_PriorityQueue& pq);
~SL_PriorityQueue();
bool isEmpty() const;
bool enqueue(const ItemType& newEntry);
bool dequeue();
//@throw PrecondViolatedExcept if priority queue is isEmpty
ItemType peekFront() const throw(PrecondViolatedExcep);
};
#endif

这是我用来测试代码的驱动程序:

#include "../src/Node.cpp"
#include "../src/LinkedSortedList.cpp"
#include "../src/SL_PriorityQueue.cpp"
#include <iostream>
int main()
{
std::shared_ptr<SL_PriorityQueue<int> > testing (new SL_PriorityQueue<int>());
testing->enqueue(7);
std::cout << testing->peekFront() << std::endl; //I set a break point here, which is where CLion throws the exception
std::cout << testing->dequeue() << std::endl;
std::cout << testing->isEmpty() << std::endl;
return 0;
}

以下是 CLion 在异常后突出显示的 SL_PriorityQueue.cpp 函数:

template <class ItemType>
bool SL_PriorityQueue<ItemType>::enqueue(const ItemType& newEntry)
{
slistPtr->insertSorted(newEntry);
return true;
}

该错误使我认为当我在上述函数中调用insertSorted时,slistPtr仍然是null。我的SL_PriorityQueue构造函数是空的,因为似乎使用智能指针他们可以管理自己的内存,这样我就不必将其设置为等于空指针。

我尝试将slistPtr设置为共享指针,以查看是否可能太多东西指向它,但我刚刚收到相同的错误。

提前感谢您提供的任何帮助!

我的SL_PriorityQueue构造函数是空的,因为似乎与 聪明的指针他们管理自己的记忆,这样我就不必 将其设置为等于空指针。

如果我理解正确的话,你在这里有点混乱。尽管unique_ptr会正确清理它拥有的内存,但它本身不会分配任何内容。最好的方法是使用 std::make_unique,您可以从构造函数调用它。

template <typename ItemType>
SL_PriorityQueue<ItemType>::SL_PriorityQueue()
: slistPtr(std::make_unique<LinkedSortedList<ItemType>>())
{
}

希望对您有所帮助!