为什么C++中stack/queue的pop()函数不返回值而返回void

转载自:http://blog.csdn.net/sxyizhiren/article/details/42506823

C++中stack,其中有两个方法:

pop(), 返回void,

top(),返回栈顶的引用。


看起来非常pop函数非常的浪费,为什么不再pop是返回值呢。

我收集到两个原因:


1.

安全原因:

假设有这个stack类

class Stack
{
    public:

    T pop();    //let pop to change the stack's internal state and return the top element

}; 

这么使用

Stack stack;

stack.push(object);

Object obj=stack.pop() ;

当我们执行Object obj=stack.pop() 时,Object的构造函数被调用,而这里是可以反生异常的,

假设这时候发生异常,丢生的栈顶元素就回不去了。


2.

效率原因:

当一个栈顶元素被弹出后,我们不得不返回这个元素的值(而不是引用),因此接收这个值的一方Object obj必然发生一次实例化。

而不同的是top函数不弹出元素,因此可以返回引用,也就不必发生实例化。

所以为了兼顾效率,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.

猜你喜欢

转载自blog.csdn.net/summer00072/article/details/80753864