Why should pop() take an argument?

前端 未结 5 828
你的背包
你的背包 2021-02-15 02:09

Quick background
I\'m a Java developer who\'s been playing around with C++ in my free/bored time.

Preface
In C++, you often see

5条回答
  •  太阳男子
    2021-02-15 02:40

    The problem with the Java approach is that its pop() method has at least two effects: removing an element, and returning an element. This violates the single-responsibility principle of software design, which in turn opens door for design complexities and other issues. It also implies a performance penalty.

    In the STL way of things the idea is that sometimes when you pop() you're not interested in the item popped. You just want the effect of removing the top element. If the function returns the element and you ignore it then that's a wasted copy.

    If you provide two overloads, one which takes a reference and another which doesn't then you allow the user to choose whether he (or she) is interested in the returned element or not. The performance of the call will optimal.

    The STL doesn't overload the pop() functions but rather splits these into two functions: back() (or top() in the case of the std::stack adapter) and pop(). The back() function just returns the element, while the pop() function just removes it.

提交回复
热议问题