警钟长鸣!

· · 个人记录

总结:

  1. 如果内核态时间(sys)很长,说明发生了大量 memcpy/memset 调用。(个人经验仅供参考)
  2. 函数返回大家伙(如 STL 容器)时写 move 或不使用逗号压行。

事情是这样的:笔者在写一道长剖板子时,采用了「vector 启发式合并」的写法。部分代码如下(其中 ds 是含有 vector 的封装结构体,使用 C++14 编译):

ds dfs(int x, int fa) {
    ds f = {};
    for (int v: e[x]) if (v != fa) {
        auto g = dfs(v, x);
        if (g.size() > f.size()) swap(f, g);
        int n = f.size(), m = g.size();
        ll v = g[m];
        f.add(v);
        F(i, 1, m) f(i, g[i] - v);
    }
    return f.push(), f.add(sz[x] - 1), f;
}

运行 n=3\times 10^5 的数据,这是它的用时:

real    0m8.711s
user    0m3.337s
sys     0m5.320s

……

将函数体的最后一行替换为

f.push(), f.add(sz[x] - 1);
return f;

或

return f.push(), f.add(sz[x] - 1), move(f);

都可以解决此问题,只需 0.3s,是不是非常神奇呢。

由此我们可以发现,x, y 与 y 并不完全等价。

翻阅 cppreference,可以发现:

  1. The following expressions are lvalue expressions: the name of a variable, ......

  2. The following expressions are prvalue expressions: a, b, the built-in comma expression, where b is an rvalue......

  3. expression may be move-eligible if it appears as the operand of a return statement......

  4. The expression is move-eligible if it is a (possibly parenthesized) id-expression that names a variable......

其实说白了就是,f(变量名)本来是左值,只是因为规则 4 才使用移动语义。

而 ...,f 是左值,并且不被规则 4 包含,然后触发了复制……

编译器没有想象中智能

参考资料:,value_category,cppreference

Automatic_move_from_local_variables_and_parameters,cppreference