Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there C++ lazy pointer?

Tags:

c++

pointers

I need a shared_ptr like object, but which automatically creates a real object when I try to access its members.

For example, I have:

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.

Is there some implementation, or I should to write my own?

like image 739
Alexander Artemenko Avatar asked May 18 '09 15:05

Alexander Artemenko


People also ask

Does C use smart pointers?

Smart Pointers in C++Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator. auto_ptr, shared_ptr, unique_ptr and weak_ptr are the forms of smart pointer can be implemented by C++ libraries.

Can a pointer be any type in C?

void pointer in C / C++A void pointer can hold address of any type and can be typecasted to any type.

Is smart pointers C ++ 11?

Introduction of Smart PointersC++11 comes up with its own mechanism that's Smart Pointer. When the object is destroyed it frees the memory as well. So, we don't need to delete it as Smart Pointer does will handle it.

What is the point of pointers in C?

The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location. The purpose of pointer is to save memory space and achieve faster execution time.


1 Answers

It's very little effort to roll your own.

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;
like image 146
ephemient Avatar answered Oct 24 '22 21:10

ephemient