0

I have a bunch of unique_ptrs for database connections. They get checked out by different parts of the code to run database queries, then returned (std::move) back to the container for next use.

I want to keep track of all instances of these unique_ptrs (db connections) by a weak_ptr to close the connections on a termination signal.

When unique pointers are checked out, I don't have a good way to call on all of them to close their connections immediately, since I don't have a link to them. Can I keep track of them by a container of weak_ptrs and access them via that container?

Is is possible to move a weak_ptr reference to a unique_ptr?

I am new to C++. I see other questions on SO, but they are different than what I want to do.

How can I do something like this:

unique_ptr<sql::Connection> conn_to_kill = std::move(weak_ptr_to_connection);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Sean
  • 1
  • 8
    `std::weak_ptr` can only hold a non-owning reference to a `std::shared_ptr` and cannot be used with `std::unique_ptr`. A `std::shared_ptr` or one acquired from `std::weak_ptr` cannot be moved into a `std::unique_ptr` as that would violate ownership. You need to use `std::shared_ptr` or rethink what you're trying to accomplish. – Captain Obvlious Jan 19 '23 at 19:06
  • 3
    Adding to @CaptainObvlious: Suppose this were possible. You have a weak reference to a unique_ptr. Suppose you ask the weak reference, "Please produce the unique_ptr that you are tracking (assuming it still exists)", and the unique_ptr does indeed exist. What does it return? It can't return another unique_ptr - that would violate uniqueness! What could do is have a weak reference to a shared_ptr>, so that everybody shares the same unique_ptr. But that's pointless: You may as well just use a shared_ptr in the first place. – Raymond Chen Jan 19 '23 at 19:17
  • No, there isn't anything like weak_ptr for unique_ptr. You would have to create your own. – user253751 Jan 19 '23 at 19:50
  • At best, you can move the value of a unique_ptr i.e. transfer the ownership from one to another: [demo on coliru](http://coliru.stacked-crooked.com/a/398073af97a0ff30). (Not sure whether this is what you're looking for...) – Scheff's Cat Jan 20 '23 at 06:38

0 Answers0