#include <iostream>
class DatabaseConnection {
private:
void* dbHandle;
public:
// 默认构造函数
DatabaseConnection() : dbHandle(nullptr) {
std::cout << "Default constructor called." << std::endl;
}
// 带参数构造函数
DatabaseConnection(const std::string& connectionInfo) {
// 这里模拟根据连接信息获取连接句柄
std::cout << "Constructor with parameters called, initializing connection with: " << connectionInfo << std::endl;
dbHandle = reinterpret_cast<void*>(new char[1]); // 简单模拟获取资源
}
// 拷贝构造函数
DatabaseConnection(const DatabaseConnection& other) {
if (other.dbHandle) {
// 深拷贝,这里简单模拟重新获取相同资源
dbHandle = reinterpret_cast<void*>(new char[1]);
std::cout << "Copy constructor called, deep - copying resource." << std::endl;
} else {
dbHandle = nullptr;
}
}
// 移动构造函数
DatabaseConnection(DatabaseConnection&& other) noexcept {
dbHandle = other.dbHandle;
other.dbHandle = nullptr;
std::cout << "Move constructor called, moving resource." << std::endl;
}
// 析构函数
~DatabaseConnection() {
if (dbHandle) {
delete[] reinterpret_cast<char*>(dbHandle);
std::cout << "Destructor called, releasing resource." << std::endl;
}
}
};