CS100 · Fall 2026 · Programming Assignment
HW5: Dynamic Arrays and STL
C++17 · Online questions and Git submission on Gradescope
Released · 发布
Sun, Nov 15 · 12:00
⏰ Deadline · 截止
Sun, Nov 29 · 23:59
Overview
HW5 consists of four problems on two Gradescope assignments. Problem 1 is a set of online objective questions; Problems 2–4 are programming problems. This is the first C++ homework: the programming problems are submitted as .cc files and compiled with g++ -std=c++17.
| Problem | Topic | Gradescope assignment | Points |
|---|---|---|---|
| Problem 1 | Basic knowledge V (C++: classes, STL) | HW5_p1 (online questions) | 110 |
| Problem 2 | Dynamic Array | HW5_programming | 100 |
| Problem 3 | Dynamic Array 2.0 | HW5_programming | 100 |
| Problem 4 | Smart Pointers | HW5_programming | 100 |
Problem 1 lives on the online assignment HW5_p1. The full statements of the three programming problems are below. Read the Submission section carefully before your first upload.
Basic knowledge V
110 pts · HW5_p1Problem 1 is a set of online questions on the Gradescope assignment HW5_p1: questions about C++ — classes, constructors, copy control, and the standard template library.
Answer the questions directly on Gradescope. Your total score is visible immediately after submission, and you may resubmit as many times as you like until the deadline; the latest answers count.
Dynamic Array
100 pts · HW5_programmingImplement your own version of the dynamic array Dynarray class. This is almost the same as the class example.
Expected usage
A Dynarray represents an "array" of ints, the length of which is determined at run-time and the elements are stored in dynamically allocated memory. A Dynarray should manage the memory it uses correctly: it should allocate adequate memory when initialized, and deallocate the memory when it is destroyed to avoid memory leaks.
Initialization
Let n be a non-negative integer and x be an integer. Let begin and end be of type const int * satisfying begin <= end, with begin pointing at the first element of some array and end pointing at the element after the last element of that array. A Dynarray can be constructed in the following ways:
Dynarray a;— an empty "array" whose length is0(default-initialization).Dynarray a(n);— an "array" of length n, all elements value-initialized. Note: a constructor with one parameter also defines a type conversion. To forbid the abuse likeDynarray a = 42;, add theexplicitkeyword to this constructor.Dynarray a(n, x);— an "array" of length n, all elements initialized to be x.Dynarray a(begin, end);— an "array" of lengthend - begin, whose elements are obtained from the range[begin, end).Dynarray b = a;— copy-initialization (see copy control below).Dynarray b = std::move(a);— initialization through a move (see copy control below).
Copy control
Our Dynarray adopts the value semantics: copy-initialization (Dynarray b = a;, Dynarray b(a);, Dynarray b{a};) should allocate another block of memory for b and copy the elements from a. After that, the data owned by a and b are independent: modification to some element in a should not influence the elements in b.
Dynarray c = std::move(a); (likewise Dynarray c(std::move(a));) initializes c by moving resources from a. After that, a should be an empty dynamic array that can be safely destroyed or assigned to. This operation should be noexcept, and it should not involve any operations that might throw exceptions (e.g. new/new[] expressions).
Copy-assignment b = a; makes b a copy of a (independent storage, as above). Move-assignment b = std::move(a); makes b take over everything previously owned by a, leaving a an empty dynamic array safe to destroy or assign to; it is noexcept and must not involve potentially-throwing operations. Both assignment operators must be self-assignment safe.
Basic information
Let a be an object of type const Dynarray:
a.size()— returns the length of the "array" (the number of elements), of typestd::size_t(defined in<cstddef>).a.empty()— returns aboolindicating whether theDynarrayis empty (length zero).
Element access
Let a be an object of type Dynarray and ca an object of type const Dynarray, and let n be a non-negative integer:
a.at(n)— returns a reference to the element indexed n, both readable and modifiable.ca.at(n)— returns a reference-to-constto the element indexed n, read-only (ca.at(n) = 42;must be a compile error).
To keep consistent with the behaviors of the standard library containers, Dynarray::at should do bounds-checking. If n is not in the range [0, a.size()), throw std::out_of_range{"Dynarray index out of range!"} (defined in <stdexcept>).
Example
Write your code in p2.cc as a header-style file (with include guards, no main). The starter package contains a compile_test.cc with compile-time checks of your implementation: members missing, const qualifier missing, or incorrect return types will be detected at compile time.
#include "p2.cc" // in e.g. example1.cc #include <algorithm> #include <iostream> void reverse(Dynarray &a) { for (int i = 0, j = a.size() - 1; i < j; ++i, --j) std::swap(a.at(i), a.at(j)); }
Sample session from example1.cc (provided in the starter): input 5 then 1 2 3 4 5 prints [5, 4, 3, 2, 1], then 5, then 42 (copy independence).
No main in p2.cc. The autograder compiles a course driver that #includes your file; p2.cc must define the class Dynarray and nothing else. Do not use std::vector/std::deque/std::list in this problem: the grader checks for forbidden includes.
Dynamic Array 2.0
100 pts · HW5_programmingThis problem is based on the Dynarray you wrote in the last problem. Before adding anything new to it, your Dynarray should meet all the requirements of Problem 2 first. Submit the complete class in p3.cc (header-style, no main); it is graded independently of your Problem 2 submission.
Type alias members
The standard library containers have many type alias members for the purpose of supporting generic types. Do the same in your Dynarray — define the following public type alias members:
| Type alias member | Definition |
|---|---|
Dynarray::size_type | std::size_t |
Dynarray::value_type | int |
Dynarray::pointer | int * |
Dynarray::reference | int & |
Dynarray::const_pointer | const int * |
Dynarray::const_reference | const int & |
We will eventually make this Dynarray a class template Dynarray<T> (in a later homework). To make your work easier by then, make full use of the type alias members: change new int[n] to new value_type[n], change int & to reference, etc.
Subscript operator
The Dynarray should support the subscript operator, so that we can use a[i] instead of a.at(i). Let a be an object of type Dynarray or const Dynarray. The behavior of a[i] should be exactly the same as a.at(i), except that the subscript operator does not perform bounds checking: no exception is thrown if i >= a.size().
Relational operators
The Dynarray should support the six relational operators <, <=, >, >=, == and !=. These operators perform lexicographical comparison of two Dynarrays: element by element, the first mismatching element defines which is less or greater; if one range is a prefix of the other, the shorter is less; equal ranges of the same length are equal; an empty range is less than any non-empty range.
You are not allowed to write loops or recursions in these six functions. Go through the standard library algorithms and find the appropriate ones. Since C++17 does not have compiler-generated comparison operators, implement operator< and operator== first and define the rest in terms of them. Make your implementation depend only upon operator< and operator== of the element type. You may define them as members or non-members.
Output operator
We want to print a Dynarray directly using operator<<:
int arr[] = {1, 2, 3, 5}; Dynarray a(arr, arr + 4); Dynarray b; std::cout << a << '\n' << b << std::endl;
Output:
[1, 2, 3, 5] []
Elements are separated by a comma followed by a space; the content starts with [ and ends with ]; an empty array prints [].
No main in p3.cc, and the same forbidden-container rule as Problem 2 applies.
Smart Pointers
100 pts · HW5_programmingRaw pointers obtained from new expressions require manual deletes, which is error-prone: early returns, exceptions, or simply forgetting. In this problem you will implement two smart pointers of your own, following the ideas of std::unique_ptr and std::shared_ptr:
UniquePtr<T>: exclusive ownership. Copying is disabled; moving transfers the ownership of the managed object.SharedPtr<T>: shared ownership based on reference counting. Copying increments the counter; when the counter drops to zero, the managed object is destroyed.
Write your code in p4.cc as a header-style file (with include guards, no main). The autograder compiles a course driver that #includes your file and runs the tests.
Do not include <memory> (and do not use std::unique_ptr/std::shared_ptr): the grader checks for forbidden includes.
How the two smart pointers differ
Before writing code, make sure the design difference is clear. A UniquePtr<T> is the only pointer to its object, so it can safely delete the object in its own destructor. A SharedPtr<T> may share its object with other SharedPtrs, so no single one of them may decide alone when to destroy it — instead, they share a counter, and the last one out destroys the object:
UniquePtr — one owner
UniquePtr<Widget> p(new Widget(1)); // auto q = p; // ERROR: no copy auto q = std::move(p); // ownership moves to q // now p owns nothing, q owns the Widget
SharedPtr — shared owners
SharedPtr<Widget> p(new Widget(1)); // count == 1 auto q = p; // count == 2 q = SharedPtr<Widget>{}; // count == 1, alive p = SharedPtr<Widget>{}; // count == 0, destroyed
Task 1: UniquePtr<T>
UniquePtr<T> is a class template that manages an object of type T obtained from a new expression. It exclusively owns the object: when the UniquePtr is destroyed, the object it manages is destroyed via a delete expression.
Construction.
UniquePtr<T> p;— default-construction:powns nothing (a "null" pointer — a well-defined state, not an indeterminate value).UniquePtr<T> p(new T(...));— takes ownership of the object pointed to by the raw pointer.
Copy control. Copying is disabled: declare the copy constructor and the copy assignment operator as = deleted — there is no reasonable meaning of copying an exclusive owner. Moving is the transfer of ownership:
UniquePtr<T> q = std::move(p);— move-construction:qtakes over the object managed byp; afterwardspowns nothing.noexcept.q = std::move(p);— move-assignment:qfirst destroys the object it currently manages (if any), then takes over the object managed byp; afterwardspowns nothing.noexceptand self-assignment safe (q = std::move(q)must keep the object alive).- The destructor destroys the managed object (if any) via
delete.
Observation. Let p be a UniquePtr<T> owning some object, and cp a const UniquePtr<T>:
*p— reference to the managed object, readable and modifiable;*cp— reference-to-const(read-only).p->member— equivalent to(*p).member.static_cast<bool>(p)—trueiffpowns some object. The conversion should beexplicit, so thatp + 1does not compile by accident.p.get()— the raw pointer (T *), ornullptrifpowns nothing. Never releases ownership.
Ownership manipulation.
p.reset(q);(whereqis aT *) —pdestroys the object it currently manages (if any), then takes ownership ofq.reset()with no argument isreset(nullptr):powns nothing afterwards.T *raw = p.release();—pgives up the ownership without destroying the object and returns the raw pointer;powns nothing afterwards. The caller is then responsible fordeleteing the returned pointer.
Example — every Widget below is destroyed exactly once, and no delete is ever written by hand:
void work() { UniquePtr<Widget> p(new Widget(1)); if (someCondition()) return; // Widget(1) destroyed here automatically p.reset(new Widget(2)); // Widget(1) destroyed, Widget(2) owned } // Widget(2) destroyed at end of scope
Task 2: SharedPtr<T>
SharedPtr<T> manages an object with shared ownership: many SharedPtr<T>s may point to the same object. Use reference counting to decide when the object should be destroyed: maintain a counter of how many SharedPtr<T>s point to the object. Construction from a raw pointer starts the counter at 1. Copying points to the same object and increments the counter. When a SharedPtr that shares an object is destroyed, or is assigned a new value, the counter of its (old) object is decremented; if it reaches zero, the managed object is destroyed via delete — exactly once.
Construction.
SharedPtr<T> p;— owns nothing.SharedPtr<T> p(new T(...));— takes ownership; the reference counter starts at 1.SharedPtr<T> q = p;— copy-construction:qpoints to the same object asp; the counter is incremented.
Assignment.
q = p;— copy-assignment: the counter of the object currently managed byqis decremented (and that object destroyed if the counter reaches zero), thenqpoints to the object managed bypand that counter is incremented. Must be self-assignment safe — think carefully about the order of "increment" and "decrement", orq = qmay destroy the only owner's object.SharedPtr<T> r = std::move(p);— move-construction: steals the pointer without touching the counter;powns nothing afterwards.q = std::move(p);— move-assignment:qreleases its current object (decrement/destroy as above), then takes over everything fromp;powns nothing afterwards.noexcept.
Destruction. The destructor decrements the counter of the shared object; when it reaches zero, the managed object is destroyed exactly once. Watch the counter and the object lifetimes through nested scopes:
SharedPtr<Widget> a(new Widget(7)); // count == 1 { SharedPtr<Widget> b = a; // count == 2 } // b dies: count == 1, Widget alive std::cout << a.use_count(); // prints 1
Observation. *p, p->member, explicit operator bool and get() behave exactly like their UniquePtr counterparts. In addition, p.use_count() returns the current value of the reference counter (std::size_t; 0 for an empty SharedPtr).
Implementation hint: store the counter somewhere out of the object itself — a small "control block" allocated together with the ownership, holding the pointer and the counter, works well. Ask yourself: who destroys the control block, and when? Both templates only need to work for non-array T. Do not use <memory>; everything else in the standard library is allowed (but little is needed).
How you will be graded
The course driver contains, for each task, compile-time checks (missing members, missing const, wrong return types or a copyable UniquePtr fail to compile) and runtime tests that construct, copy, move, reset and destroy your smart pointers around a logging Widget type: every construction and destruction is recorded, and the resulting event stream must match the expected one exactly. Run your code with -fsanitize=address while developing — a wrong reference count almost always shows up as a double free or a leak in the sanitizer, long before the output diff does.
Submission
Starter package: download HW5_student_starter.zip — the three source files (already correctly named), the class examples for Problem 2, and a README that walks you through the compile commands. Fill in your code and submit the files as-is.
Problem 1: answer the online questions on the Gradescope assignment HW5_p1. You may update your answers any number of times before the deadline.
Problems 2–4: submit to the Gradescope assignment HW5_programming. Write one C++ source file per problem, named exactly p2.cc, p3.cc and p4.cc. Submission is via a GitHub repository only (no file upload): create a private repository with the three files at the top level, then on Gradescope choose the GitHub submission method, select your repository and branch. Each problem is graded independently, and the three problems show up as three rows of 100 points each.
The autograder builds your code with the course's own trusted commands — you do not need to write a Makefile. P2 and P3 are header-style files (no main): the course driver #includes your file and runs its tests through it. P4 is compiled together with the course's test driver.
Compilation
You compile the code by typing a g++ command yourself in the terminal (WSL). p2.cc/p3.cc have no main; the provided example files #include "p2.cc" for you, so test by compiling one of them (or your own test file) directly:
g++ example1.cc -o example1 -std=c++17 -Wall -Wpedantic -Wextra -Werror -fsanitize=undefined -fsanitize=address
Replace the file names to build the other problems or your own tests. compile_test.cc checks the interface requirements of Problem 2 at compile time — building it successfully means your class signature is correct.
What the autograder requires
On Gradescope your code is built by the course's trusted commands (any Makefile you submit is ignored) with g++ -std=c++17, strict warnings treated as errors (-Wall -Wpedantic -Wextra -Werror -Wzero-as-null-pointer-constant) and the sanitizers (-fsanitize=undefined -fsanitize=address). Fix every warning before you submit — on the OJ side a warning is an error.
Each problem's 100 points are split across its test cases, and a problem's score is the sum of the test cases you pass. A run is stopped if it exceeds its time limit, produces excessive output, or crashes.
Tip: press the up arrow key in the terminal to bring back the last command you typed — you will never have to retype a long g++ line.