C++ 转发引用错误时,终端进程终止
我正试着写一份清单。我使用C++ 转发引用错误时,终端进程终止,c++,templates,C++,Templates,我正试着写一份清单。我使用转发引用来处理左值和右值。但是在insertAsPrev函数中调用new运算符时,程序出错 template <typename T> class ListNode { friend class List<T>; public: using pnode = ListNode<T> *; ListNode() : prev(nullptr), next(nullptr) {}
转发引用
来处理左值
和右值
。但是在insertAsPrev
函数中调用new
运算符时,程序出错
template <typename T>
class ListNode
{
friend class List<T>;
public:
using pnode = ListNode<T> *;
ListNode() : prev(nullptr), next(nullptr) {}
ListNode(T const & e, pnode p=nullptr, pnode n=nullptr)
: data(e), prev(p), next(n) {}
template <typename X>
ListNode(X && e, pnode p=nullptr, pnode n=nullptr)
: data(std::forward<X>(e)), prev(p), next(n) { cout << "ini\n";}
template <typename X>
pnode insertAsPrev(X && e);
template <typename X>
pnode insertAsNext(X && e);
private:
T data;
pnode prev;
pnode next;
};
template <typename T>
template <typename X>
ListNode<T> * ListNode<T>::insertAsPrev(X && e)
{
cout << "insert as prev\n";
pnode node = new ListNode<T>(std::forward<X>(e), prev, this);
prev->next = node; prev = node;
return node;
}
template <typename T>
List<T>::List(initializer_list<T> il)
{
for (T i : il)
{
cout << "initializer list\n" ;
insertAsLast(i);
}
}
template <typename T>
template <typename X>
ListNode<T> * List<T>::insertAsLast(X && e)
{
cout << "as last\n";
++_size; return trailer->insertAsPrev(std::forward<X>(e));
}
int main()
{
List<int> = {1, 2, 3, 4, 2, 3, 1};
}
我的问题:程序似乎在
new
操作中停止。是什么导致了这个问题
我应该使用重载来处理左值和右值情况吗 您的
列表
构造函数没有初始化您在insertaslat
中使用的拖车
成员,这会导致未定义的行为,从而导致崩溃updated@YunnoschWhat是否列出?我建议只问一个问题。第二个似乎不是第一个的细节(这很好)。我忘了启动标题
和尾部
指针。而insertAsPrev
中的prev
是nullptr
。我应该结束我的问题还是删除它。抱歉打扰了。
initializer list
as last
insert as prev
The terminal process terminated with exit code: 2816