MST

星途 面试题库

面试题:C++ 复杂场景下构造函数声明形式规范及资源管理

设计一个类 `DatabaseConnection` 用于管理数据库连接资源。它包含一个指向数据库连接句柄的指针成员变量(假设为 `void* dbHandle`),并且要遵循 C++ 构造函数声明形式规范。要求写出默认构造函数、带参数构造函数(参数用于初始化数据库连接相关信息,进而获取连接句柄)、拷贝构造函数、移动构造函数以及析构函数。在构造函数和析构函数中要合理处理资源的获取与释放,在拷贝构造函数和移动构造函数中要符合资源管理的语义(例如深拷贝、资源转移等)。
40.5万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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;
        }
    }
};