0%

返回值

起初没有理解这段话,之后顿悟到表达式结果需要是prvalue才能调用移动构造函数,也就是说是一个字面值或者不具名的临时对象。此后写了以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <bits/stdc++.h>

template<class T>
class info
{
private:
T x;
public:
explicit info(T x = 0) : x(x) { std::cout << 777 << std::endl; }

info(const info &rhs) : x(rhs.x) { std::cout << 444 << std::endl; }

info(info &&rhs) noexcept: x(rhs.x)
{
rhs.x = 0;
std::cout << 555 << std::endl;
}

friend info operator+(const info &lhs, const info &rhs)
{
info c;
c.x = lhs.x + rhs.x;
return c;
}

T get() const noexcept { return x; }
};

int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
info a(1), b(2);
info c = a + b;
std::cout << c.get() << std::endl;
return 0;
}

输出:

1
2
3
4
5
777
777
777
555
3

输出时一度发现没有555,后来查到是编译器默认开启返回值优化(RVO),添加编译命令"-fno-elide-constructors"关闭返回值优化后得到想要的答案。