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

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

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

这是我的 SL_PriorityQueue class 的头文件:

#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 设为共享指针,看看是否有太多东西指向它,但我收到了同样的错误。

在此先感谢您提供的任何帮助!

My constructor for SL_PriorityQueue is empty since it seems that with smart pointers they manage their own memory such that I don't have to set it equal to a null pointer.

如果我没听错的话,你有点混淆了。虽然 unique_ptr 会正确地清理它拥有的内存,但它自己不会分配任何东西。最好的方法是使用 std::make_unique,您可以从构造函数中调用它。

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

希望对您有所帮助!