C++ tips: Why the pop method of STL stack does not return a value

Or why they don't combine the functionality of pop/top method into one function?

We know that the pop method pops the top element of the stack, change the stack's internal state but returns nothing; and the top method returns a reference to the top element on the stack, but does not change the stack's internal state. If we want to pop the top element and then remove it from the stack, we need to call both top and pop:

 

stack<Gadget> gadgets;

gadget = gadgets.top();

gadgets.pop();

 

One of the reasons is exception safety, suppose we combine functionalities into one function:

template<class T>

class stack

{

public:

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

};

 

Then suppose the client write below code:

 

Gadget gadget;                 //call default constructor of Gadget

gadget = gadgets.pop();  //call operator= of Gadget

 

or

 

Gadget gadget = gadgets.pop();  //call copy constructor of Gadget

 

If operator= or copy constructor throws exception, then we will be in trouble: the stack's internal state has been changed, but we have not get the popped element.

Actually, any mutator function (function that changes an object's internal state) should not directly return an object to avoid the issue discussed here.