Boost logo

Boost :

From: Angus Leeming (angus.leeming_at_[hidden])
Date: 2004-01-08 08:09:03


David Abrahams wrote:

> "Joe Gottman" <jgottman_at_[hidden]> writes:
>
>>> > One major use for unique() is copy-on-write. The code would
>>> > look
>>> > something like:
>>> >
>>> > void write_to(shared_ptr<Foo> p, const Foo &newValue)
>>> > { // For simplicity, assume p.get() != 0
>>> > if (p.unique()) {
>>> > *p = newValue;
>>> > } else {
>>> > p.reset(new Foo(newValue));
>>> > }
>>> > }
>>> >
>>> > Under the current definition of unique(), this code is
>>> > impossible to make thread-safe if weak_ptrs might exist.
>>>
>>> Would it work just as well if unique() returned weak_count?
>>>
>>
>> It would work better. If nobody is using weak_ptrs then
>> weak_count equals
>> 1 if and only if shared_count equals 1. And if weak_ptrs are
>> possible, then having unique() depend on weak_count guarantees that
>> this code is thread-safe.
>
> Are there any other use cases? I think I was the one to argue for
> "unique" in the first place, and COW was the only use I had in
> mind...

I have this code that use shared_ptr<>::use_count() to
ascertain whether to remove an item from a cache:

Is that the sort of thing you are interested in?
Angus

class Cache : boost::noncopyable {
public:
        /** Add a graphics file to the cache.
         * Only actually adds the file if it isn't alrady present.
         */
        void add(std::string const & file) const;

        /** Remove a file from the cache.
         * Only actually removes the file if no other user is
         * storing an ItemPtr.
         */
        void remove(std::string const & file) const;

        /// Returns \c true if the file is in the cache.
        bool inCache(std::string const & file) const;

        /** Get the cache item associated with file.
         * Returns an empty container if there is no such item.
         *
         * IMPORTANT: whatever uses an image must make a local copy of this
         * ItemPtr. The boost::shared_ptr<>::use_count() function is
         * used to ascertain whether or not to remove the item from the cache
         * when remove(file) is called.
         *
         * You have been warned!
         */
        typedef boost::shared_ptr<CacheItem> ItemPtr;
        ItemPtr const item(std::string const & file) const;

private:
        typedef std::map<string, ItemPtr> CacheType;
        CacheType cache;
};


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk