代码之家  ›  专栏  ›  技术社区  ›  MK.

C++避免指针的惯用方法是什么?

  •  2
  • MK.  · 技术社区  · 8 年前

    我有一个方法,将const ref作为一个集合。我想打电话给m.b.传一套给它。如果我有。所以我先看看我有没有一套:

    const auto& it = mapOfSets.find("token");
    if (it != std::end(mapOfSets)) {
      myFunction(it.second);
    } else {
      MySetType emptySet;
      myFunction(emptySet);
    }
    

    做这件事的惯用方法是什么?我不喜欢上面的方法,因为对myFunction的调用重复了两次,而且还有一些其他参数,所以有一些不必要的代码重复。

    我的C程序员只想改变函数接受指针,如果没有找到NulLPTR,但是我觉得C++现在都是为了避免指针……

    3 回复  |  直到 7 年前
        1
  •  1
  •   Chris Drew    8 年前

    如果您编写了一个helper函数来查找映射中的一个集合,那么您可以在没有找到任何内容的情况下返回对特殊空集的引用:

    const MySetType& find(const MyMapType& mapOfSets, const std::string& key) {
        auto it = mapOfSets.find(key);
        if (it != std::end(mapOfSets)) {
            return it->second;
        }
        static const MySetType emptySet;
        return emptySet;
    }
    

    那么您的调用代码就是:

    myFunction(find(mapOfSets, "token"));
    
        2
  •  3
  •   Rakete1111    8 年前

    可以使用条件运算符:

    myFunction(it != mapOfSets.end() ? it->second : MySetType{});
    

    不过,我不认为有一种惯用的方式。

        3
  •  0
  •   JiaHao Xu    8 年前

    也许是手写的 optional_reference 可以参考的 nullptr 但是威尔 throw 当取消对它的引用并且没有额外的 bool

    #include <stdexcept>
    #include <memory>
    
    class null_access_exception: public std::logic_error
    {
        using base = std::logic_error;
    public:
        null_access_exception():
            base("Try to dereference null optional_reference!")
        {}
    };
    
    template <class Ptr_t>
    class optional_reference
    {
        using self = optional_reference;
        using reference = decltype(*std::declval<Ptr_t>());
        Ptr_t ptr = nullptr;
    
    public:
        optional_reference() = default;
        optional_reference(const self&) = default;
    
        self& operator = (const self&) = delete;
    
        template <class U>
        constexpr optional_reference(U &&obj) noexcept: 
            ptr(std::addressof(obj))
        {}
    
        constexpr explicit operator bool() const noexcept
        { return has_value(); }
    
        constexpr bool has_value() const noexcept
        { return ptr != nullptr; }
    
        constexpr auto& value() const
        {
            if (!has_value())
                throw null_access_exception();
    
            return *ptr;
        }
    
        template <class U>
        constexpr auto& value_or(U &&obj) const noexcept
        {
            if (has_value())
                return *ptr;
            else
                return reference(std::forward<U>(obj));
        }
    };
    

    然后

    1. 改变 myfunction 可选\u参考

    2. 像下面一样包起来。

      constexpr const static auto null_set(); { myfunction(ref.value_or(null_set));