zoukankan      html  css  js  c++  java
  • STL中的stack的pop函数为什么不返回值?

    在数据结构C++语言描述——应用标准模板库(STL)中的解释如下:

    pop()返回类型:为什么pop()返回viod,而不是类型T呢?

    也就是说,为什么先用top(),然后用pop()来访问和删除站定的元素,而不是把它们合并一个返回类型T的成员函数。

    这种设计有很好的理由。如果pop()返回栈顶元素,则必须按值返回,而不是按引用返回。按引用返回是不可行的,因为元素

    在栈中已经不存在,必须在按引用返回之前现将其存储到某个地方。如果选用动态内存,除非动态内存最终被删除,否则将导致内存泄露。

    按照数值返回效率很差,因为它包含对类型T的复制构造函数的调用。让pop()返回数值将会导致潜在的内存问题或效率很低下,

    因此最好让它什么数值也不返回,而是通过使用top()来得到栈顶的数值。

    下面是CSDN的解释:

    以前没有仔细想过,今天看异常安全部分,才知道了其中的缘由:

    假设pop需要返回一个值,实现如下

    template<class T>
    T stack<T>::pop()
    {
      if( vused_ == 0)
      {
        throw "pop from empty stack";
      }
      else
      {
        T result = v_[vused_-1];
        --vused_;
        return result; 
      }
    }

    看起来没什么问题,但是考虑这种情况:
    T t = s.pop();
    如果此时把函数的返回值拷贝到变量t的时候产生了异常,那么刚才的s pop出来的值就消失了。一般来说,更改函数不应当以传值的方式返回对象。

    除了异常安全,还有以下原因:
    概念上显得清晰
    保证一个函数只确定地完成一项特定的功能
    使得函数之间的耦合度降低 

    官方解释:

    One might wonder why pop() returns void, instead of value_type. That is, why must one use top() and pop() to examine and remove the top element, instead of combining the two in a single member function? In fact, there is a good reason for this design. If pop() returned the top element, it would have to return by value rather than by reference: return by reference would create a dangling pointer. Return by value, however, is inefficient: it involves at least one redundant copy constructor call. Since it is impossible for pop() to return a value in such a way as to be both efficient and correct, it is more sensible for it to return no value at all and to require clients to use top() to inspect the value at the top of the stack.

    http://blogs.msdn.com/b/zhanli/archive/2010/06/29/c-tips-why-the-pop-method-of-stl-stack-does-not-return-a-value.aspx

    http://stackoverflow.com/questions/4892108/c-stl-stack-question-why-does-pop-not-throw-an-exception-if-the-stack-is-em

  • 相关阅读:
    待整理
    字符编码 【ZZ】
    python中的数据类型,存储,实现
    python中的浅拷贝和深拷贝
    算法比较-SVM和logistic回归
    机器学习中的范数规则化之(一)L0、L1与L2范数
    全排列的编码和解码----康托编码
    C++的const类成员函数
    Trie树的简单描述(需后续总结)
    UWP 手绘视频创作工具技术分享系列
  • 原文地址:https://www.cnblogs.com/youxin/p/2612696.html
Copyright © 2011-2022 走看看