optional 与 move

move

1
2
3
4
5
6
7
std::optional<T> opt = /* ... */;

// bad
auto x = std::move(opt.value());

// good
auto x = std::move(opt).value(); 

rvo

 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class LifeTime {
	int a_ = 0;
	public:
    LifeTime(int a):a_(a){
        std::cout << "LifeTime(): " << a_ << std::endl;
    }

    ~LifeTime() {
        std::cout << "~LifeTime(): " << a_ << std::endl;
    }

	LifeTime(const LifeTime&) {
        std::cout << "LifeTime(const LifeTime&): " << a_ << std::endl;
    }

	LifeTime(LifeTime&& other) noexcept {
		this->a_ = other.a_;
        std::cout << "LifeTime(LifeTime&&): " << a_ << std::endl;
    }

	LifeTime& operator=(const LifeTime&) {
        std::cout << "LifeTime& operator=(const LifeTime&): " << a_ << std::endl;
        return *this;
    }

	LifeTime& operator=(LifeTime&&) noexcept {
        std::cout << "LifeTime& operator=(LifeTime&&): " << a_ << std::endl;
        return *this;
    }
};

//break RVO
std::optional<LifeTime> create_v1() {
	LifeTime a{ 1 };
	return a;
}

//break RVO
std::optional<LifeTime> create_v2() {
	return LifeTime{2};
}

//break RVO
std::optional<LifeTime> create_v3() {
	std::optional<LifeTime> opt;
	opt = LifeTime{ 3 };
	return opt;
}

std::optional<LifeTime> create_v4() {
	std::optional<LifeTime> opt;
	opt.emplace(4);
	return opt;
}

std::optional<LifeTime> create_v5() {
	return std::optional<LifeTime>{5};
}

std::optional<LifeTime> create_v6() {
	return std::optional<LifeTime>{std::in_place, 6};
}