boostorg / boostorg/ptr_container

[Feature Request] Need containers of guaranteed actual `std::weak_ptr`

Open
#43 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
18
Forks
42
PR merge metrics
No merged PRs in 30d

Description

Let's consider a motivating example of the code that is simple semantically but it's data flow is ugly:
```
void move_all_to_top(std::list>& child_cookies)
{
for (auto it = child_cookies.begin(); it != child_cookies.end(); ) {
boost::shared_ptr cookie = it->second.lock();

if (cookie) {
cookie->y = 100;
++it;
} else {
child_cookies.erase(it++);
}
}
}
```

Having looked at this, I wish I had a container from which expired elements are automatically removed each time it's being accessed. Does anybody agree with me?

Imagine we have `boost::weak_ptr_list` and then it becomes possible to reimplement the given example in the simpliest way:
```
void move_all_to_top(boost::weak_ptr_list& child_cookies)
{
for (Cookie& cookie : child_cookies) {
cookie.y = 100;
}
}
```
So, as you could see now, the semantic of that code was actually simple. And more over it becomes possible to use STL algorithms with container of weak pointers:
```
Cookie get_first_top(const boost::weak_ptr_list& child_cookies)
{
const auto it = std::ranges::find_if(child_cookies, [](const Cookie& cookie) { return cookie.y > 0; });
if (it == child_cookies.end()) {
throw std::runtime_error("not found");
}
return *it;
}
```

My proposal is to support containers of weak pointers on the Boost Pointer Container library side. Not only list - we also want to store weak pointers in associative containers and I suppose containers like `boost::weak_ptr_set` and `boost::weak_ptr_map` would be nice to have.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.