c – std :: stack元素销毁顺序
发布时间:2020-12-16 10:05:38 所属栏目:百科 来源:网络整理
导读:是否有关于std :: stack元素的销毁顺序的保证? 我有一个类来管理一组服务的生命周期.由于可能存在服务相互依赖性,因此构建和销毁的顺序很重要 – 服务应按其创建的相反顺序销毁. 我以为我会使用std :: stack std :: unique_ptr Service以此目的.知道堆栈是
是否有关于std :: stack元素的销毁顺序的保证?
我有一个类来管理一组服务的生命周期.由于可能存在服务相互依赖性,因此构建和销毁的顺序很重要 – 服务应按其创建的相反顺序销毁. 我以为我会使用std :: stack< std :: unique_ptr< Service>>以此目的.知道堆栈是一个容器适配器,并猜测这可能会影响它的破坏语义,我搜索了,但是I couldn’t find any documentation(第800页)保证了std :: stack元素的破坏顺序. 最后,我写了一个小测试: struct Squealer { Squealer() { static int instance_count = 0; this->instance = ++instance_count; } ~Squealer() { std::cout << "Destroying instance " << instance << std::endl; } int instance; }; int main(int argc,char *[] argv) { { std::stack<Squealer> squealers; squealers.emplace(); squealers.emplace(); squealers.emplace(); } std::cout << "...done" << std::endl; } 结果如预期: Destroying instance 3 Destroying instance 2 Destroying instance 1 ...done 我应该依靠这种行为吗? std :: stack是否保证了天真的破坏顺序,或者我应该采取(通常很容易)弹出它直到它清楚的步骤? 解决方法std::stack 不是Container,它是一个容器适配器.它需要您实际要用于存储元素的Container的第二个参数:
template< class T,class Container = std::deque<T> > class stack; 堆栈< T>的破坏语义.将是deque< T>的那些.然而,由于deque< T>的破坏顺序,这对你没有多大帮助.未标明该标准.实际上,没有为任何序列容器指定它. 如果破坏顺序很重要,那么你应该做以下两件事之一:或者提供一个新的容器,它最后会破坏它的元素: template <class T> struct my_deque : std::deque<T> { using std::deque<T>::deque; ~my_deque() { while (!this->empty()) this->pop_back(); } }; template <class T> using my_stack = std::stack<T,my_deque<T>>; 或者提供自己的堆栈实现,其析构函数会弹出所有元素: template <class T,class Container = std::deque<T>> struct ordered_stack : std::stack<T,Container> { using std::stack<T,Container>::stack; ~ordered_stack() { while (!this->empty()) { this->pop(); } } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |