Skip to content
Exercise · Memory and Smart Pointers · lesson 11 of 12

Exercise: owning buffer on unique_ptr

Write two functions. std::unique_ptr<int[]> make_filled(int n, int value) creates an array of n numbers equal to value and returns a unique_ptr that owns it. int sum(const std::unique_ptr<int[]>& p, int n) returns the sum of the first n numbers of the array p.

  • make_filled(3, 7) → the array 7 7 7
  • sum(make_filled(3, 7), 3) → 21
  • the array 2 -3 10 1, n is 3 → sum(p, n) returns 9

Constraints: n is 1 to 1000 in make_filled and 0 to the array length in sum; sum returns 0 for n = 0.

owning_buffer.cpp — cpp
cpp · 10 lines
Ctrl+Enter run · Esc leave editor