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

Download starter (ZIP)

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.

ProblemTopicGradescope assignmentPoints
Problem 1Basic knowledge V (C++: classes, STL)HW5_p1 (online questions)110
Problem 2Dynamic ArrayHW5_programming100
Problem 3Dynamic Array 2.0HW5_programming100
Problem 4Smart PointersHW5_programming100

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.

P1

Basic knowledge V

110 pts · HW5_p1

Problem 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.

P2

Dynamic Array

100 pts · HW5_programming

Implement 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:

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:

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:

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.

P3

Dynamic Array 2.0

100 pts · HW5_programming

This 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 memberDefinition
Dynarray::size_typestd::size_t
Dynarray::value_typeint
Dynarray::pointerint *
Dynarray::referenceint &
Dynarray::const_pointerconst int *
Dynarray::const_referenceconst 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.

P4

Smart Pointers

100 pts · HW5_programming

Raw 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:

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.

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:

Observation. Let p be a UniquePtr<T> owning some object, and cp a const UniquePtr<T>:

Ownership manipulation.

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.

Assignment.

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.