MST

星途 面试题库

面试题:C++中const指针在复杂数据结构和多线程环境下的深入应用

假设有一个C++类`DataContainer`,其中包含一个`const int *`类型的成员变量,用于指向一个动态分配的整数数组。类中有成员函数用于初始化这个指针、读取数组元素以及在多线程环境下安全地修改数组元素。请实现这个类,并详细说明在多线程环境下如何保证`const`指针的使用既符合常量性原则,又能确保线程安全。
18.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <mutex>

class DataContainer {
private:
    const int *data;
    std::mutex dataMutex;
public:
    DataContainer() : data(nullptr) {}

    void initialize(const int *arr, size_t size) {
        std::lock_guard<std::mutex> lock(dataMutex);
        if (data) {
            delete[] data;
        }
        data = new int[size];
        for (size_t i = 0; i < size; ++i) {
            data[i] = arr[i];
        }
    }

    int readElement(size_t index) const {
        std::lock_guard<std::mutex> lock(dataMutex);
        if (index < 0 || index >= getSize()) {
            throw std::out_of_range("Index out of range");
        }
        return data[index];
    }

    void modifyElement(size_t index, int value) {
        std::lock_guard<std::mutex> lock(dataMutex);
        if (index < 0 || index >= getSize()) {
            throw std::out_of_range("Index out of range");
        }
        int *mutableData = const_cast<int*>(data);
        mutableData[index] = value;
    }

    size_t getSize() const {
        // 假设我们有一个方法能获取数组大小,这里简单返回0,实际应用需根据具体逻辑实现
        return 0; 
    }

    ~DataContainer() {
        std::lock_guard<std::mutex> lock(dataMutex);
        if (data) {
            delete[] data;
        }
    }
};

多线程环境下const指针使用的说明

  1. 常量性原则

    • data成员变量声明为const int *,这意味着指针本身不能被修改指向其他地址。
    • readElement函数声明为const,保证在读取数组元素时不会修改对象的状态。
  2. 线程安全

    • 使用std::mutex来保护对data指针及其指向的数组的所有访问。std::lock_guard在构造时自动锁定互斥锁,在析构时自动解锁,确保在多线程环境下,对data的操作不会产生竞态条件。
    • 对于modifyElement函数,虽然dataconst指针,但通过const_cast将其转换为可修改的指针,在加锁保护下进行修改操作,这样既保证了线程安全,又符合const指针的常量性原则(指针本身不能被随意修改指向其他地址)。