Search code examples
c++boostshared-ptr

Does boost::optional trigger a ref count on shared_ptr?


I'm trying to get a function to return an optional value from my map. So something like this:

boost::optional<V> findValue(const K& key) {
    boost::optional<V> ret;
    auto it = map.find(key);
    if (it != map.end()) {
        ret = it->second;
    }
    return ret;
}

If V happens to be a shared_ptr type of some kind, does the assignment to ret trigger a reference count?


Solution

  • Yes, it has to. boost::optional stores a copy, so for a shared_ptr, this means there is a copy of the shared_ptr and that means the reference count must be increased.

    Note that as long as the boost::optional is empty, i.e., it doesn't contain a value of shared_ptr, there is no object whose reference count is fiddled with. In other words, an empty boost::optional does not contain an (empty or otherwise) shared_ptr.

    The requested "semantics" can't really work because you keep one shared_ptr in the map and you return a shared_ptr.

    However, you may return a boost::optional<const V&>:

    boost::optional<const V&> findValue(const K& key) {
        auto it = map.find(key);
        if (it != map.end()) {
            return boost::optional<const V&>( it->second );
        }
        return boost::optional<const V&>();
    }
    

    but make sure that the reference remains valid while you keep/use it.