zoukankan      html  css  js  c++  java
  • 【C++17】std::optional

    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!
    
  • 相关阅读:
    ASP.NET验证控件的使用 拓荒者
    读书笔记:MFC单文档应用程序结构分析 拓荒者
    MFC单文档(SDI)全屏程序的实现 拓荒者
    jQuery的animate函数
    设备尺寸杂谈:响应性Web设计中的尺寸问题
    Yeoman学习与实践笔记
    IE对文档的解析模式及兼容性问题
    推荐给开发和设计人员的iPad应用
    几个移动应用统计平台
    颜色、网页颜色与网页安全色
  • 原文地址:https://www.cnblogs.com/sunbines/p/15332877.html
Copyright © 2011-2022 走看看