Search code examples
c++stdstdqueue

Standard queue misunderstanding


I have a simple C++ structure that build a std::queue with argv from the main.

It then provide a method ::cunext to return current value before poping it from the queue.

It appears that if I call this method as parameters for a function, it will revert the parameters as:

wut(cunext(), cunext());

With [1, 2] as entry on main, it give me the following output:

first param is 2
second param is 1

Is that a std::queue misunderstanding of my part?

The guilty code:

#include <iostream>
#include <queue>

using namespace std;

struct Args
{
    public:
        typedef std::string Arg;

        Args(int argc, char* argv[]);

        Arg current() const;
        Arg cunext();

    private:
        std::queue<std::string> q_args; ///< Queue of arguments as std::string objects.
};

Args::Args(int argc, char* argv[]):
    q_args()
{
    for(int i=1; i<argc; i++)   // build queue for arguments
    {
        q_args.push(*(++argv));   // skip first argument (as for path)
    }
};

inline Args::Arg Args::current() const
{
    return q_args.front();
};

inline Args::Arg Args::cunext()
{
    Arg ret = current();
    q_args.pop();
    return ret;
};

void wut(std::string bad, std::string good)
{
    cout << "first param is " << bad << endl;
    cout << "second param is " << good << endl;
}

int main(int argc, char* argv[])
{
    Args args(argc, argv);
    wut(args.cunext(),args.cunext());
    return 0;
}

Solution

  • Your understanding of std::queue is correct, as it is pointed out in the documentation. However, keep in mind that in C/C++, the standard doesn't specify the order in which the arguments are passed to the function (which is defined in the ABI), nor the order in which they are evaluated. The compiler you're using decided to evaluate them right to left, another one could have chosen left to right.