topskill.dev
CoursesTracks
0
All courses/C++ ProgrammingPrefer the Rule of Zero
Lifetime and Ownership
6 / 7
← C++ Programming
○Welcome to C++○Change a Message○Write Two Lines○Read a Program○Comments and Spacing○Name a Value○Update a Value○Build an Announcement Card✦Module Quiz
○Choose a Type○Characters and Booleans○Keep a Constant○Arithmetic and Precedence○Division and Remainders○Convert a Number○Format a Price○Calculate a Receipt✦Module Quiz
○Compare Values○Combine Conditions○Choose with if○Choose an Alternative○Choose Between Ranges○Select with switch○Pick a Short Result○Price a Ticket✦Module Quiz
○What Is a Loop?○Repeat with While○Count with For○Build a Running Total○Run at Least Once○Stop or Skip○Rows and Columns○Plan Seating for a Workshop✦Module Quiz
○Return a Result○Pass Arguments○Perform an Action○Keep Names Local○Declare Before Use○Supply a Default Argument○Overload a Function○Build Price Helpers✦Module Quiz
○Store and Join Text○Read Characters Safely○Find and Slice Text○Change a String○Read Values from Text○Write a Text Report✦Module Quiz
○Keep a Fixed Set of Counts○Add Values to a Vector○Visit Every Value○Revise a List Safely○Read Rows and Columns○Recognize a Raw Array○Summarize Shelf Stock✦Module Quiz
○Give a Value Another Name○Read Without Copying a Collection○Let a Function Update the Caller○Point to an Existing Value○Handle a Missing Target○Separate a Fixed Target from Read-Only Access○Keep Borrowed Access Within Its Lifetime✦Module Quiz
○Keep Related Fields in a Struct○Read and Update Records in Functions○Give States Meaningful Names○Keep a Collection of Records○Report Stock by Record and State✦Module Quiz
○Introduce a Class○Initialize with a Constructor○Protect an Invariant○Read a Const Object○Compose Small Objects○Share a Class Constant○Copy an Object○Grant a Friend Access○Build a Basket✦Module Quiz
○Follow a Scope○Observe a Destructor○Allocate and Release○Own with unique_ptr○Transfer Ownership●Prefer the Rule of Zero✦Module Quiz
○Understand Iterators○Sort a Range○Find and Count○Write a Lambda○Capture a Value○Accumulate a Total○Look Up with map○Keep Unique Values○Use a Stack and a Queue○Work at Both Ends○Insert in a List○Organize a Packing List✦Module Quiz
○Organize with Namespaces○Name a Type○Compute with constexpr○Check an Assumption○Write a Function Template○Write a Class Template○Overload an Operator○Pass a Function○Follow Recursion✦Module Quiz
○Extend a Class○Override a Virtual Function○Use an Abstract Base○Avoid Object Slicing○Destroy Through a Base○Check a Derived Type○Choose Composition✦Module Quiz
○Read Binary Flags○Combine Bit Masks○Respect Numeric Limits○Return a Status○Repeat a Random Sequence○Use Math Functions○Diagnose a Wrong Result✦Module Quiz
○Create the Catalog○Find a Book○Lend and Return○Summarize the Shelves○Print the Library Report○Where to Go Next✦Module Quiz

Prefer the Rule of Zero

A class that owns data does not automatically need hand-written cleanup. Strings and vectors already manage their own storage. If your class contains these members directly, their destructors run automatically when the enclosing object is destroyed.

The rule of zero is a design guideline: prefer classes that do not define custom destructors, copy constructors, copy assignments, move constructors, or move assignments. Compose them from members that already manage their resources correctly. Ordinary constructors and useful application operations are still welcome; “zero” refers to those special resource-management functions, not to every member function.

The compiler's generated memberwise behavior then follows the members' behavior. A class containing a string and a vector can be copied as an independent value. A class containing a unique pointer will not be copyable by default, because that member forbids copying. The rule of zero does not promise every class can be copied; it helps keep ownership consistent with the types you chose.

cpp
#include <iostream>
#include <vector>
struct Readings {
    std::vector<int> values;
};
int main() {
    Readings original{{4, 6}};
    Readings revised = original;
    revised.values.push_back(8);
    std::cout << original.values.size() << ' ' << revised.values.size() << '\n';
}

The example prints 2 3. The vector member supplies both independent copying and automatic cleanup. This explains why the notebook copy in the previous section needed no custom copying code either. Your Plan uses the same approach with a string and a vector. The copy is already made in main; append the new stop inside addStop(). The unchanged original count and label let you check that adding a stop did not disturb the copied data.

Your Task

  1. Implement addStop() using the vector's push_back. The revised plan must have 2 stops, the original must retain 1, and the copied label must remain Saturday.

Edit main.cpp, then press Run to inspect the Console. Press Submit to check your work. Keep the supplied probes in place.

Take the Quiz →
Files
  • ⋄main.cpp
Loading editor…
Press Run to execute your code.