This question already has answers here:
Undefined behavior and sequence points
                                
                                    (5个答案)
                                
                        
                                5年前关闭。
            
                    
这是代码:

std::string Query_Set::get_sql() const throw()
{
    std::stringstream out;
    int counter = 0;

    out << "WHERE " << time_name << " >= :start_time_" << counter++ << " AND " << time_name << " <= :finish_time_" << counter++ " AND something_else = :" << counter++;

    return out.str();
}


这段代码很简单,但是当我打印出此String时,它做了一些奇怪的事情:

"WHERE time >= :start_time_2 AND time <= :finish_time_1 AND something_else = :0"


我错过了一些简单的事情吗?为什么计数器会倒退?

最佳答案

在C ++中,未定义对表达式的参数求值的顺序。第二个counter++可能早于第一个。我什至在Clang和GCC中也看到过此类表达式的不同行为。

关于c++ - C++中奇怪的std::stringstream行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25379100/

10-13 08:06