forked from changkun/modern-cpp-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.4.string.view.cpp
More file actions
29 lines (24 loc) · 741 Bytes
/
Copy path4.4.string.view.cpp
File metadata and controls
29 lines (24 loc) · 741 Bytes
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
//
// 4.4.string.view.cpp
// chapter 04 containers
// modern c++ tutorial
//
// created by changkun at changkun.de
// https://github.com/changkun/modern-cpp-tutorial
//
#include <iostream>
#include <string>
#include <string_view>
// std::string_view is a non-owning, read-only view over a character
// sequence; passing it avoids copying and accepts both std::string and
// string literals.
void print(std::string_view sv) {
std::cout << sv << " (size = " << sv.size() << ")" << std::endl;
}
int main() {
std::string_view sv = "hello, world";
print(sv.substr(0, 5)); // "hello", no allocation
std::string s = "from std::string";
print(s); // implicit conversion, no copy
print("from a literal");
}