Hard
Object pool with a reference held past release
What happens when this program runs?
main.cpp
class Connection { public: int id = 0; std::string lastQuery; };
class ConnectionPool {
public:
Connection& acquire() {
if (free_.empty()) free_.push_back(std::make_unique<Connection>());
auto conn = std::move(free_.back());
free_.pop_back();
Connection& ref = *conn;
inUse_.push_back(std::move(conn));
return ref;
}
void release(Connection& c) {
for (auto it = inUse_.begin(); it != inUse_.end(); ++it) {
if (it->get() == &c) {
free_.push_back(std::move(*it));
inUse_.erase(it);
return;
}
}
}
private:
std::vector<std::unique_ptr<Connection>> free_, inUse_;
};
int main() {
ConnectionPool pool;
Connection& c1 = pool.acquire();
c1.lastQuery = "SELECT 1";
pool.release(c1); // c1 handed back; caller keeps using the reference
Connection& c2 = pool.acquire(); // pool hands the SAME object back out
c2.lastQuery = "SELECT 2";
std::cout << c1.lastQuery << "\n"; // c1 is stale but still 'valid' memory-wise
}17 of 44 in Design Patterns