1. 程式人生 > >為什麼C++中stack的pop()函式不返回值而返回void

為什麼C++中stack的pop()函式不返回值而返回void

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.

---------------------