C++赋值副作用

Ale*_* B. 6 c++ tuples visual-studio-2012

在尝试确保两个变量的升序时,我在Visual Studio 2012 C++编译器中遇到了奇怪的异常,可以通过以下代码片段来说明

    double x1 = 2;
    double x2 = 1;
    std::tie(x1, x2) = std::minmax(x1, x2);
    std::cout << "x1 = " << x1 << ",   x2 = " << x2 << "\n";
Run Code Online (Sandbox Code Playgroud)

人们会期望x1是1而x2是2.但它们不是.代替

    //output:
    //x1 = 1,   x2 = 1
Run Code Online (Sandbox Code Playgroud)

有没有什么好的解释,只是为了确保不再陷入类似的陷阱?

Ben*_*ley 4

std::minmax通过引用返回其参数。您的语句所发生的情况是,首先x1被分配 的值x2,即 1。然后,x2被分配 的值x1,原为 2,但现在为 1。

如果你要内联所有内容,它可能看起来像这样:

// using pointers because references can't be rebound
double *less, *greater;

if (x1 <= x2)
{
    less = &x1;
    greater = &x2;
}
else
{
    // in your case, this is the branch taken
    less = &x2;
    greater = &x1;
}

x1 = *less;       // less points to x2, so now both x1 and x2 = 1
x2 = *greater;    // greater points to x1, and x1 = 1, so this assignment is redundant
Run Code Online (Sandbox Code Playgroud)

我认为您的困惑部分来自于认为(或希望)作业会同时发生,但事实并非如此。当您分配 atuple或 a时pair,子对象会按从左到右的顺序分配。