• 【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!
    
  • 相关阅读:
    iOS开发之Xcode8兼容适配iOS 10资料整理笔记
    C#流概述
    C#回调实现的一般过程
    ASP.Net MVC的学习
    RAID基本知识
    Infiniband基本知识
    [转]开源实时视频码流分析软件:VideoEye
    [转]高分一号的落后与特色
    [转]MVC,MVP 和 MVVM 的图示
    图文助你打开MS SQL Serever的ldf和mdf文件
  • 原文地址:https://www.cnblogs.com/sunbines/p/15332877.html
Copyright © 2020-2023  润新知