BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bslstl_ownerless

Detailed Description

Outline

Purpose

Provide an ordering for shared and weak pointers.

Classes

Canonical header: bsl_memory.h

See also
bslstl_sharedptr

Description

This component provides the C+11 standard binary comparison functor, bsl::owner_less, that determines the order of two smart pointer objects by the relative order of the address of their bslma::SharedPtrRep data. Note that this class is an empty POD type.

Usage

This section illustrates intended use of this component.

Example 1: Basic Use of owner_less<void> {#bslstl_ownerless-example-1-basic-use-of-owner_less}

Suppose we need a map accepting shared pointers as keys. We also expect that this container will be accessible from multiple threads and some of them will store weak versions of smart pointers to break reference cycles. To avoid excessive conversions we can use a transparent comparator to enable heterogeneous lookup with bsl::weak_ptr objects as parameters for search functions.

First, we create a container and populate it:

Map;
Map container;
bsl::shared_ptr<int> sharedPtr1 = bsl::make_shared<int>(1);
bsl::shared_ptr<int> sharedPtr2 = bsl::make_shared<int>(2);
bsl::weak_ptr<int> weakPtr1(sharedPtr1);
container[sharedPtr1] = 1;
container[sharedPtr2] = 2;
Definition bslstl_map.h:619
Definition bslstl_sharedptr.h:1830
Definition bslstl_sharedptr.h:3705
Definition bslstl_ownerless.h:119

Now, we make sure, that shared pointers can be used to perform lookup:

Map::const_iterator iter = container.find(sharedPtr1);
assert(container.end() != iter );
assert(1 == iter->second);
iter = container.find(sharedPtr2);
assert(container.end() != iter);
assert(2 == iter->second);

Finally, we simulate the situation of accessing the container from another thread and perform lookup using weak pointers:

iter = container.find(weakPtr1);
assert(container.end() != iter );
assert(1 == iter->second);
bsl::weak_ptr<int> weakPtr3(bsl::make_shared<int>(3));
iter = container.find(weakPtr3);
assert(container.end() == iter);