#2601·drogon

possible exception in db connexions creations

Author: chmounirCreated Sep 18, 2026Updated Sep 18, 2026

the call of newConnection with the capture of this and usage of shared_from_this() may throuw exception of bad_weak_ptr, is it possible to replace this code :

void DbClientImpl::init()
{
    // LOG_DEBUG << loops_.getLoopNum();
    loops_.start();
    if (type_ == ClientType::PostgreSQL || type_ == ClientType::Mysql)
    {
        for (size_t i = 0; i < numberOfConnections_; ++i)
        {
            auto loop = loops_.getNextLoop();
            loop->runInLoop([this, loop]() { newConnection(loop); });
        }
    }
    else if (type_ == ClientType::Sqlite3)
    {
        sharedMutexPtr_ = std::make_shared<SharedMutex>();
        assert(sharedMutexPtr_);

        for (size_t i = 0; i < numberOfConnections_; ++i)
        {
            newConnection(nullptr);
        }
    }
}

by this one :

void DbClientImpl::init() {
  // LOG_DEBUG << loops_.getLoopNum();
  loops_.start();
  if (type_ == ClientType::PostgreSQL || type_ == ClientType::Mysql) {
    for (size_t i = 0; i < numberOfConnections_; ++i) {
      auto loop = loops_.getNextLoop();
      std::weak_ptr<DbClientImpl> weak_current_client = shared_from_this();
      loop->runInLoop([weak_current_client, loop]() {
        if (auto current_client = weak_current_client.lock()) {
          current_client->newConnection(loop);
        }
      });
    }
  } else if (type_ == ClientType::Sqlite3) {
    sharedMutexPtr_ = std::make_shared<SharedMutex>();
    assert(sharedMutexPtr_);

    for (size_t i = 0; i < numberOfConnections_; ++i) {
      newConnection(nullptr);
    }
  }
}

capturing a weak and calling a lock on it at the begining of the loop prevent the throw if the client had been destroyed befor the end of connection creation.