std::optional
1. vlaue_or 函数使用
1 #include <iostream> 2 #include <optional> 3 #include <string> 4 5 std::optional<std::string> create(bool b) 6 { 7 if(b) return "Godzilla"; 8 return {}; 9 } 10 11 int main() 12 { 13 std::cout << "create(false) return: " << create(false).value_or("empty") << std::endl; 14 std::cout << "create(true) return: " << create(true).value_or("empty") << std::endl; 15 return 0; 16 }
输出:
create(false) return: empty create(true) return: Godzilla
2. reset函数使用
void reset() noexcept;
用例:
1 #include <iostream> 2 #include <optional> 3 4 struct Base 5 { 6 std::string s; 7 Base(std::string str) : s(std::move(str)) { std::cout << "constructed!" << std::endl; } 8 ~Base() { std::cout << "destructed! " << std::endl; } 9 10 Base(const Base &b) : s(b.s) { std::cout << "copy constructed!" << std::endl; } 11 12 Base &operator=(const Base &rhs) 13 { 14 s = rhs.s; 15 std::cout << " copy assigned!" << std::endl; 16 return *this; 17 } 18 19 Base &operator=(Base &&rhs) 20 { 21 s = std::move(rhs.s); 22 std::cout << " move assigned!" << std::endl; 23 return *this; 24 } 25 }; 26 27 int main() 28 { 29 std::cout << "Create empty optional: " << std::endl; 30 std::optional<Base> opt; 31 32 std::cout << "Construct and assign value: " << std::endl; 33 opt = Base("Lorem ipsum dolor sit amet, consectetur adipiscing elit nec."); 34 35 std::cout << "Read option: " << std::endl; 36 opt.reset(); 37 std::cout << "End example." << std::endl; 38 }
输出:
Create empty option: Construct and assign value: constructed! copy constructed! destructed! Read option: destructed! End example!