初始化指向类实例的智能指针并访问其方法
Initializing a smart pointer to an instance of class and accessing its methods
所以,我正在尝试使用排序列表实现优先级队列。我的优先级队列类继承自排序列表类。当我在驱动程序中测试其功能时,我的排序列表类工作正常,但是当我尝试测试优先级队列的实现时,我遇到了"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>>())
{
}
希望对您有所帮助!
相关文章:
- 通过指向指针数组的指针访问子类的属性
- 使用指针访问数组中的对象数据成员
- 无法通过指针访问对象的成员
- decltype:使用指针访问类的静态成员
- 是否可以使用指针访问变量以避免直接编辑变量?
- 为什么 C++ 地址中的矢量无法通过原始指针访问
- 使用指针访问数组元素时出现意外结果
- 使用指针访问数组的值
- C++继承从基类指针访问派生类中的非虚拟函数
- 如何使用指针访问成对向量的元素
- 为什么有些库提供无指针访问,而另一些库则不提供
- 如何通过引用或指针访问二维矢量
- 使用指针访问参数接收的结构中的元素时内存泄漏
- 我正在学习C++,我不能使用指针访问参考吗?(举个例子)
- 复制堆栈上的成员值或使用指针访问它?
- C++娜娜 如何从全局列表框*指针访问列表框内的索引 0 上的按钮?
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 从指针访问 Kaguya Lua 状态
- 说明通过指针访问非静态类成员函数
- 有没有办法使用初始化到第一行的指针访问 2d 数组的第二行?