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 whypop()returnsvoid, instead ofvalue_type. That is, why must one usetop()andpop()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. Ifpop()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 forpop()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 usetop()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

原文链接: https://www.cnblogs.com/youxin/archive/2012/07/28/2612696.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/57186

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午8:00
下一篇 2023年2月9日 上午8:01

相关推荐