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

Exercise: playlist of shared songs

Write a class Playlist that shares ownership of its songs with their other owners; a song is a std::shared_ptr<std::string> holding its title. void add(const std::shared_ptr<std::string>& song) adds a song to the end, and void remove(const std::string& name) removes every song titled name. int size() const returns the number of songs, and std::string title(int index) const returns the title of song number index; add the fields yourself.

intro and rain are the songs "Intro" and "Rain", and the playlists mine and yours start empty. Each example continues the previous one:

  • after mine.add(intro), mine.add(intro), mine.add(rain) and yours.add(intro): intro.use_count() → 4
  • after *intro = "Outro": yours.title(0) → "Outro"
  • after mine.remove("Outro"): mine.size() → 1, intro.use_count() → 2

Constraints: index is from 0 to size() - 1, and a song added several times counts that many times in size() and use_count(). A song stays in the playlist even with no other owners, and remove with a title not in the playlist changes nothing.

owner_count.cpp — cpp
cpp · 21 lines
Ctrl+Enter run · Esc leave editor