简体   繁体   中英

c++ cout strange behavior with a custom Stack class

I have a custom stack class. Most of the code can be seen here:
Member functions of a templated class, that take a template type as argument

I fill the stack like so:

stack <int> Astack;
Astack.Push(1); Astack.Push(2); Astack.Push(3); Astack.Push(4);

Then I do this:

cout << Astack.Pop() << Astack.Pop() << Astack.Pop() << Astack.Pop() <<endl;

and get this: 1234
However, if I do this:

cout << Astack.Pop(); cout << Astack.Pop(); cout << Astack.Pop(); cout << Astack.Pop();

I get this: 4321, which is obviously what I want.

So, what gives?

The order of evaluation of the function calls is unspecified. Your first expression basically boils down to this:

cout << a << b << c << d;

Each of a , b , c , and d are calls to Astack.Pop() . The compiler can generate code that evaluates those calls in any order it chooses.

You should avoid writing expressions that rely on a particular order of evaluation of parts of the expression. In general, it's not safe (and even when it is safe, it is usually quite confusing).

In the first version the arguments to cout are evaluated from right to left. You never actually specify which order they should be evaluated in, so the one on the right is evaluated first, popping the 4, and so on.

There is something known as Unspecified Behaviour defined by the ISO C++ Standard. Your code-snippet is just an example of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM