大佬教程收集整理的这篇文章主要介绍了c – 通用堆栈类的异常安全代码,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <iostream> #include <memory> #include <exception> class stk_exception:public exception { virtual const char* what() const throw() { return "stack underflow"; } } stk_ex; template <class T> struct node { T data; node<T> *next; }; template <class T> class stack_generic { public: stack_generic() : _head(nullptr) { } void push(T X) { node<T> *temp(new node<T>()); temp->data = x; temp->next = _head; _head = temp; } void pop() { if (_head == nullptr) { throw stk_ex; } else { node<T> *temp = _head; _head = _head->next; delete temp; return; } } T top() { T x = T(); if (_head == nullptr) { throw stk_ex; } else { return _head->data; } } private: node<T> *_head; }; int main() { stack_generic<int> s; s.push(1); s.push(2); std::cout << s.top(); s.pop(); std::cout << s.top(); s.pop(); }
我可以使用STL列表/向量来实现RAII,但我想使用原始指针.因此,当我使用unique_ptr将头指针包装在堆栈中时,它会抛出一个编译错误“对于调用unique_ptr,default_delete没有匹配的函数.这里有什么问题?有人可以建议我该怎样做才能使这个类异常安全吗?谢谢!
#include <iostream> #include <memory> #include <exception> template <class T> class node { public: node(T data,std::shared_ptr<node<T>> next) : _data(data),_next(next) { } T data() const { return _data; } std::shared_ptr<node<T>> next() const { return _next; } private: T _data; std::shared_ptr<node<T>> _next; }; template <class T> class stack_generic { public: stack_generic() : _head(nullptr) { } void push(T X) { _head = std::make_shared<node<T>>(x,_head); } T pop() { if (_head == nullptr) { throw std::underflow_error("underflow"); } else { std::shared_ptr<node<T>> temp = _head; _head = _head->next(); return temp->data(); } } private: std::shared_ptr<node<T>> _head; }; int main() { stack_generic<int> s; s.push(1); s.push(2); std::cout << s.pop(); std::cout << s.pop(); }
请注意以下事项:
>使用命名空间std;是不好的做法.>对现代C程序使用Nullptr而不是NULl.>使用下溢的异常来创建已定义的行为.>在节点上使用访问器方法来创建只读对象.>为节点使用构造函数.>使用例如std :: shared_ptr自动释放数据.
以上是大佬教程为你收集整理的c – 通用堆栈类的异常安全代码全部内容,希望文章能够帮你解决c – 通用堆栈类的异常安全代码所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。