Question: I often find myself wanting to write code like this:

```
class MyClass
{
public:
  void addObject(std::unique_ptr<Object>&& newObject);

  void removeObject(const Object* target);

private:
  std::set<std::unique_ptr<Object>> objects;
};

```

However, much of the std::set interface is kind of useless with std::unique\_ptrs since the lookup functions require std::unique\_ptr parameters (which I obviously don't have because they're owned by the set itself).

I can think of two main solutions to this.

1. Create a temporary unique\_ptr for lookup. For example, the above removeObject() could be implemented like:

```
void MyClass::removeObject(const Object* target)
{
  std::unique_ptr<Object> targetSmartPtr(target);
  objects.erase(targetSmartPtr);
  targetSmartPtr.release();
}

```
2. Replace the set with a map of raw pointers to unique\_ptrs.

```
  // ...
  std::map<const Object*, std::unique_ptr<Object>> objects;
};

```

However, both seem slightly stupid to me. In solution 1, erase() isn't noexcept, so the temporary unique\_ptr might delete the object it doesn't really own, and 2 requires double the storage for the container unnecessarily.

I know about Boost's pointer containers, but their current features are limited compared to modern C++11 standard library containers.

I was recently reading about C++14 and came across "Adding heterogeneous comparison lookup to associative containers". But form my understanding of it, the lookup types must be comparable to the key types, but raw pointers aren't comparable to unique\_ptrs.

Anyone know of a more elegant solution or an upcoming addition to C++ that solves this problem?

Answer: 
You can try to use boost::multi\_index\_container with additional indexing by Object\*.
Something like this:

```
typedef std::unique_ptr<Object> Ptr;
typedef multi_index_container<
  Ptr,
  indexed_by<
    hashed_unique<Ptr>,
    ordered_unique<const_mem_fun<Ptr,Object*,&Ptr::get> >
  >
> Objects;

```

Fore more information see [Boost Multi-index Containers documentation](http://www.boost.org/doc/libs/1_54_0/libs/multi_index/doc/index.html) 

Or may be you can use std::shared\_ptr everywhere, or use raw pointers in set instead?

Why you need to lookup by raw pinter? If you store it anywhere and check that object with this pointer is valid then better to use std::shared\_ptr for storing in container and std::weak\_ptr for other objects. In this case before usage you don't need lookup by raw pointer at all.
You're using unique pinters here. This means, your set has unique ownership of objects. Now, this should mean that if object does exist, it's either in the set or you have unique pointer with it. You don't even need to look up the set in this case.

But to me it looks like it's not hte case. I suppose you're better off with shared pointer in this case. Just store shared pointers and pass them around since someone beside this set clearly stores them.