简体   繁体   中英

Is it possible to have an array of smart pointers that automatically updates its values with their index?

In C++, is there a way to write an array of smart pointers that automatically updates the pointed-to values with their index in the array? The pointed-to values have a member to store the index, similar to an intrusive refcount.

I am interested in writing a heap with updatable priorities. If the values in the heap were always updated to point to their index inside the heap storage, without special knowledge inside the heap algorithm, it would be easy to follow that link back into the heap when changing the value's priority. Knowing the position of the changed item, the heap invariant could then be quickly restored.

This is my attempt at a basic implementation. I would prefer to parameterize Container s reference to the global array without making instances larger than one pointer, and it would be good to improve safety. It would be more useful if it was also a random access iterator.

class Contained {
    public:
        uintptr_t index;
};

class Container {
    public:
        Contained *value;

    Container& operator=(Container& other);
};

Container foobars[4];

Container& Container::operator=(Container& other) {
    this->value = other.value;
    this->value->index = ((uintptr_t)this - (uintptr_t)foobars) / sizeof(this->value);
    return *this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM