Navigation
Outline:
Last modification
2025-09-04
This is smol web. If you don't like it, fix your browser.

Assignment#

Deadline: November 23rd.

We have learned to use the constructors and destructors so that a class can behave like a normal variable, but safely keep an associated resource (e.g. allocated memory, open file, or so.)

Apply this to implement a variable-length array type, called Array. Your implementation should be a work-alike of the std::vector, only reasonably simpler.

Requirements:

Remember that you need to call constructors and destructors of the objects contained in your array, so that they are correctly initialized and destroyed after use!

You can implement following bonus features to patch up other inefficiencies in the code:

Place your resulting solution to file cpparray.hpp and upload it to the correct field in the study group interface in SIS.

As a test, you can use this file which should work correctly with your implementation of Array. (Note that there’s a possibility to use std::vector instead of Array for the test — this can serve as a guideline if you are not sure about exact functionality of something.) The default test is small and may not crash even if your implementation contains errors; try increasing S to a larger value (say,

  1. to increase the failure probability.

NOTES: It is important to understand the semantic difference between “raw allocated memory” (which is the result of reserve() operation) and “allocated memory with constructors ran on it” (which is the result of resize()) — if the user only reserves the space for objects, none should be actually initialized (imagine the objects hold some large resource or lock something; the user would not like to consume these resources before he places the actual objects into the container). You can allocate raw memory using either malloc(size) or using operator new(size). Memory can be deallocated without calling a destructor using either free(ptr) or operator delete(ptr). The constructors can be ran manually on raw memory using the “placement new” syntax — new(ptr) Type(constructor_args); destructors are ran using the “pointer destruct” syntax — ptr->~Type(). Compare with ptr=new Type() and delete ptr, which combine both memory allocation and object initialization/destruction. This difference is something that is vital for understanding the RAII model of C and drawing a bold line between memory allocation (which is one resource) and object lifetime (which is a completely different resource that only requires the space provided by the previous one). Anyway, this gets philosophical very easily; for that reason you will not be penalized if your implementation does not do this completely right. The only thing you need to ensure is that all objects in the valid array size (indexes 0 to size()-1) have been initialized and will be deinitialized upon removal.