代码之家  ›  专栏  ›  技术社区  ›  Alexander Artemenko

有C++的懒惰指针吗?

  •  14
  • Alexander Artemenko  · 技术社区  · 16 年前

    shared_ptr

    例如,我有:

    class Box
    {
    public:
        unsigned int width;
        unsigned int height;
        Box(): width(50), height(100){}
    };
    
    std::vector< lazy<Box> > boxes;
    boxes.resize(100);
    
    // at this point boxes contain no any real Box object.
    // But when I try to access box number 50, for example,
    // it will be created.
    
    std::cout << boxes[49].width;
    
    // now vector contains one real box and 99 lazy boxes.
    

    4 回复  |  直到 10 年前
        1
  •  18
  •   ephemient    16 年前

    这是非常小的努力来滚自己的。

    template<typename T>
    class lazy {
    public:
        lazy() : child(0) {}
        ~lazy() { delete child; }
        T &operator*() {
            if (!child) child = new T;
            return *child;
        }
        // might dereference NULL pointer if unset...
        // but if this is const, what else can be done?
        const T &operator*() const { return *child; }
        T *operator->() { return &**this; }
        const T *operator->() const { return &**this; }
    private:
        T *child;
    };
    
    // ...
    
    cout << boxes[49]->width;
    
        2
  •  10
  •   Johannes Schaub - litb    16 年前

    boost::optional ,你可以有这样的东西:

    // 100 lazy BigStuffs
    std::vector< boost::optional<BigStuff> > v(100);
    v[49] = some_big_stuff;
    

    将构造100个懒人并分配一个实数 some_big_stuff v[49] . boost::可选 将不使用堆内存,但使用placement new在堆栈分配的缓冲区中创建对象。我会创建一个包装 boost::可选 这样地:

    template<typename T>
    struct LazyPtr {
        T& operator*() { if(!opt) opt = T(); return *opt; }
        T const& operator*() const { return *opt; }
    
        T* operator->() { if(!opt) opt = T(); return &*opt; }
        T const* operator->() const { return &*opt; }    
    private:
        boost::optional<T> opt;
    };
    

    现在使用 boost::可选 op* ):

    T& operator*() { if(!opt) opt = boost::in_place(); return *opt; }
    

    这不需要任何复制。但是,目前的增压手册不包括分配操作员过载。然而,消息来源确实如此。我不确定这只是手册中的一个缺陷,还是故意遗漏了它的文档。因此,我会使用更安全的方法,使用复制作业 T() .

        3
  •  2
  •   Dan Breslau    16 年前

    你确定a sparse matrix

        4
  •  0
  •   Head Geek    16 年前