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

标签 c++ function std-pair post-increment function-parameter

我尝试构造整数对,其中第二个整数比第一个整数大 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/

相关文章:

c++ - 条件 if 中类成员的范围

c++ - 在boost中使用make_shared和allocate_shared?

r - 为什么 R 中的 Order() 不返回正确的顺序?

php - 如何获取一个类的所有公共(public)属性作为json?

javascript - 如何清除所有 javascript 超时?

c++ - 不匹配调用 '(std::pair<unsigned int, unsigned int>) (unsigned int&, unsigned int)'

c++ - 如何检查是否正在隐式生成移动构造函数?

c++ - 如何读取 XSD 架构元素 <xs :schema 的 'Version' 属性

c++ - 将 vector <pair <double,double> 写入文件的最快方法

c++ - 输出没有临时的返回对