80. Deep Copy Assignment Buffer

You are developing a firmware-style C++ class that stores sensor readings inside a dynamically allocated byte buffer.
Each buffer instance must own its memory exclusively and follow correct ownership and lifetime rules.

Your task is to implement the copy assignment operator so that assigning one object to another using:

A = B; 

performs a deep copy.

A deep copy means:

  • The destination object allocates its own buffer
  • All bytes from the source buffer are fully duplicated
  • No memory is shared between objects

If implemented incorrectly, the program may suffer from:

  • Data corruption due to shared memory
  • Double-free errors
  • Hard-to-diagnose crashes common in embedded systems

 

What the class must support

The SensorBuffer class must implement:

  • A constructor that dynamically allocates a byte buffer of a specified size
  • A destructor that correctly frees the allocated memory
  • A copy assignment operator that:
    • Detects self-assignment
    • Releases any previously owned memory
    • Allocates a new buffer matching the source object’s size
    • Copies every byte from the source buffer

The class also provides helper functions to:

  • Modify individual buffer elements
  • Print the contents of the buffer

 

Program Flow

  1. Read an integer N1 followed by N1 byte values → initialize object A
  2. Read an integer N2 followed by N2 byte values → initialize object B
  3. Perform the assignment A = B
  4. Print the final contents of object A

After the assignment:

  • A must have the same number of elements as B
  • A must contain the same values as B
  • A must own an independent memory buffer

 

Example Input

5
1 2 3 4 5
5
9 9 9 9 9

Example Output

9 9 9 9 9 

 

Constraints

  • Buffer size ranges from 1 to 100
  • Each buffer value is in the range 0–255
  • All buffers must be dynamically allocated using new[]
  • All allocated memory must be released using delete[]
  • The copy assignment must perform a deep copy
  • Output must be space-separated with no trailing spaces

 

 

 

Loading...

Input

4 10 20 30 40 4 1 1 1 1

Expected Output

1 1 1 1