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
63
64
65
|
#include <iostream>
#include <string>
#include <algorithm>
class StringProcessor {
public:
// RVO - 返回临时对象
static std::string toUpper(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
return s; // NRVO
}
// RVO - 返回临时对象
static std::string concatenate(const std::string& a, const std::string& b) {
return a + b; // RVO - 返回临时对象
}
// NRVO with multiple return paths
static std::string process(const std::string& input, bool uppercase) {
std::string result = input;
// 一些处理
if (uppercase) {
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
} else {
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
}
// 编译器通常能对单return路径进行NRVO
// 如果有多个return,可能无法优化
return result;
}
// 更好的多路径写法
static std::string processBetter(const std::string& input, bool uppercase) {
// 直接在返回值位置构造
return uppercase ? toUpper(input) : toLower(input);
}
private:
static std::string toUpper(const std::string& s) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
return result; // NRVO
}
static std::string toLower(const std::string& s) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), ::tolower);
return result; // NRVO
}
};
int main() {
std::string hello = "Hello, World!";
// 这些调用都不会产生拷贝
std::string upper = StringProcessor::toUpper(hello);
std::string combined = StringProcessor::concatenate("Hello", "World");
std::string processed = StringProcessor::processBetter(hello, true);
std::cout << upper << "\\n";
std::cout << combined << "\\n";
std::cout << processed << "\\n";
}
|