[C++] [ICS-46] 为什么std::stack会有const T& top() const方法?Why std::stack has const T& top() const method?

C++|计算机 ComputerScience

   
   

@ZYX 写于2020年11月01日

结论 Conclusion

该方法与复制/赋值初始化有关,若没有这个方法,那么通过复制/赋值初始化的stack将会无法使用top()方法。
This method is related with copy/assignment initialization. If stack did not have this method, the const stack, which initialized through copy or assignment, could not call top() method.

Example

// if stack did not have const T& top() const method
std::stack<int> a;
a.push(3);
const std::stack<int> b(a); // copy initialization
const std::stack<int> c=a; // assignment initialization
++b.top(); // wrong.
++c.top(); // wrong
/*
vscode says the object has type qualifiers that are not compatible with the member function
*/

Difference

// stack has const T& top() const method
std::stack<int> a;
a.push(3);
const std::stack<int> b(a); // copy initialization
const std::stack<int> c=a; // assignment initialization
++b.top(); // wrong.
++c.top(); // wrong
/*
vscode says expression must be a modifiable lvalue
*/