0

Today I wrote a wrapper class to do database queries. My idea was to inherit from std::stringstream to be able to write something like this:

Statement st;
st << "SELECT name FROM user WHERE email LIKE " << st.prep("john") << ";";
st.exec();

While testing I realized that the execution order of the prep function differs depending on the compiler used. Look at this simple snippet:

#include <sstream>
#include <iostream>

unsigned nr = 0;

std::string prep() {
    std::stringstream s;
    s << nr++;
    return s.str();
}

int main(int argc, char** argv) {
    std::cout << prep() << " " << prep() << " " << prep() << "\n";
    return 0;
}

You could think that output will be "0 1 2" and yes, if compiled with icc or clang++ it behaves like that. But when compiling with g++ the output for me is "2 1 0".

Is there any way to ensure ascending execution order?

Marco
  • 1
  • 1
  • No, there is not. The `< – Cody Gray Jul 10 '16 at 15:34
  • Wait until C++17, there would be fixed order of argument evaluation for << operator – Revolver_Ocelot Jul 10 '16 at 15:36
  • I always wondered why that feature was important to anyone, @Revolver. Then, the last couple of days on Stack Overflow, I've seen like 4 questions about it. So I guess it is a common pain point. – Cody Gray Jul 10 '16 at 15:39
  • Thanks for your answers. I ended up creating a function to test if order is ascending or descending. – Marco Jul 10 '16 at 18:05
  • That is not a good idea. You should not rely on a particular order of evaluation, even if your test seems to demonstrate that there is one. Write the code so that it does not depend on any such order. There is absolutely no cost to multiple lines. – Cody Gray Jul 11 '16 at 04:33
  • You are absolutely right, this was a bad idea. – Marco Jul 13 '16 at 21:13

0 Answers0