3️⃣Buffer [18]

#include // For std::length_error

class Buffer { public: explicit Buffer(int size) : size(size) { if (size <= 0) { throw std::length_error("Buffer size must be positive"); } buffer = new char[size]; }

~Buffer() {
    delete[] buffer;  // Ensure proper deallocation in destructor
}

// Member functions to access and modify the buffer (consider bounds checking)
char getCharAt(int pos) const {
    if (pos < 0 || pos >= size) {
        throw std::out_of_range("Index out of bounds");
    }
    return buffer[pos];
}

void setCharAt(int pos, char value) const {
    if (pos < 0 || pos >= size) {
        throw std::out_of_range("Index out of bounds");
    }
    buffer[pos] = value;
}

int getSize() const { return size; }

private: char* buffer; int size; }; scrivere un costruttore di copia ed un operatore di assegnazione per la seguente classe? Indicare perché e nel caso implementare i metodi necessari. È necessario scrivere un distruttore ? Nel caso implementarlo. (12 punti)

Codice
class Buffer {
  public:
    Buffer(int size) : size(size) { }
    void allocate() {
    buffer = new char[size];
    }
    void setCharAt(int pos, char value) {
    if( pos>=0 && pos < size )
buffer[pos] = value;
}
char getCharAt(int pos){
if( pos>=0 && pos < size )
return buffer[pos];
else
return '\0';
}
int getSize() const { return size; }
private:
char* buffer;
int size;
};
Risposta

si.

Buffer(const Buffer& other) {
    data = other.data;
  }
  
Buffer& operator = (Buffer other){ //other = copia, quello di destinazione
  std::swap(size, other.size); //
  std::swap(buffer, other.buffer); //swap in due passaggi.
  return *this;
}

virtual ~Buffer(){};

L’implementazione della classe Buffer fornita nell’esercizio è a rischio di memory leak in caso di problemi. Riscrivere la classe usando l’idioma RAII (Resource Acquistion Is Initialization), e mostrare come usare la classe. (6 punti)

Risposta
#include <stdexcept>  // For std::length_error

class Buffer {
public:
    explicit Buffer(int size) : size(size) {
        buffer = new char[size];
    }

    ~Buffer() {
        delete[] buffer;  // Ensure proper deallocation in destructor
    }

    // Member functions to access and modify the buffer (consider bounds checking)
    char getCharAt(int pos) const {
        if (pos < 0 || pos >= size) {
            throw std::out_of_range("Index out of bounds");
        }
        return buffer[pos];
    }

    void setCharAt(int pos, char value) const {
        if (pos < 0 || pos >= size) {
            throw std::out_of_range("Index out of bounds");
        }
        buffer[pos] = value;
    }

    int getSize() const { return size; }

private:
    char* buffer;
    int size;
};

Last updated