gpt4 book ai didi

c++ - 使用后增量构造带有变量的整数对 std::pair

转载 作者:行者123 更新时间:2023-12-01 12:27:16 25 4
gpt4 key购买 nike

我尝试构造整数对,其中第二个整数比第一个整数大 1 :

1 2
2 3
3 4

同时使用 std::make_pair和这样的构造函数:
std::make_pair(n, n++);

但是,这会导致对是相反的:
2 1
3 2
4 3

如果我要将后增量放在第一个参数上或使用 (n+1)相反,我得到了想要的结果。

为什么它会这样?

最佳答案

来自 cppreference :

When calling a function (whether or not the function is inline, and whether or not explicit function call syntax is used), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function.



所以这里发生的事情就是这样。
int n = 0;
auto p = std::make_pair( n, n++ );

首先我们确定 make_pair的过载;我们得到:
make_pair<int&, int>( int&, int&& )

即,第一个参数是右值引用(最终绑定(bind)到 n),第二个参数是左值引用(最终绑定(bind)到 n++ 返回的临时值)。

我们评估 make_pair 的论点.它们以任意方式排序,但您会在这里看到它并不重要。

绑定(bind) nint&不复制值,它只是存储一个引用。

绑定(bind) n++int&&创建一个临时对象,复制 n 的值进去,然后设置一个副作用增加 n然后。

何时发生副作用是这里的关键。如上所述,它必须在函数 make_pair 之前的某个时间发生。叫做。

它可能发生在 n 之前对第一个参数或之后进行评估;没关系,因为我们绑定(bind)了对 n 的引用到论点。然而,在我们做 make_pair 的正文之前,它会被评估。 .

所以在 make_pair 内,保证有引用 n , 其值为 1 ,以及对值为 0 的临时对象的引用.然后它运行并返回具有这些值的一对。

看来你误解了 n++意思是——它的意思是“返回 n 的值,然后增加它”,它是 意思是“返回一个大于 n 的值 1”。

返回大于 n 的值 1 的方式是 n+1 .

关于c++ - 使用后增量构造带有变量的整数对 std::pair,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61566936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com