One rule
A reference means: this object must exist. A pointer means: this object may be missing, shared by address, or changed to point elsewhere.
Use the stricter option first. If a function does not need null, take a reference, not a pointer.
Why it matters
Many C++ bugs in student projects are not syntax bugs. They are lifetime bugs. You keep an address after the real object is gone, then the program behaves strangely.
Your repo should show that you know when data lives, who owns it, and whether a function can receive nothing.
Choose the parameter
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Safe function inputs
This pattern fits many hackathon projects: read a list, compute something, and optionally print extra details.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Expense {
string label;
int amount;
};
int totalAmount(const vector<Expense>& expenses) {
int total = 0;
for (const Expense& e : expenses) {
total += e.amount;
}
return total;
}
void addExpense(vector<Expense>& expenses, const string& label, int amount) {
expenses.push_back({label, amount});
}
void printFirst(const vector<Expense>* expenses) {
if (expenses == nullptr || expenses->empty()) {
cout << "No expenses\n";
return;
}
cout << expenses->at(0).label << " " << expenses->at(0).amount << "\n";
}
int main() {
vector<Expense> trip;
addExpense(trip, "chai", 20);
addExpense(trip, "metro", 60);
cout << totalAmount(trip) << "\n";
printFirst(&trip);
printFirst(nullptr);
}Dangling addresses
Do not return a reference or pointer to a local variable. The local dies when the function ends.
Also be careful with addresses of vector elements. push_back can move the vector storage, so old pointers or references to elements may become invalid.
int& badRef() {
int marks = 95;
return marks; // bad: marks dies here
}
Expense* badPtr() {
Expense e{"idli", 40};
return &e; // bad: e dies here
}Use AI carefully
If you ask ChatGPT or Gemini to refactor C++ code, ask it to explain every pointer and reference it uses.
Check three things in the answer: can this be nullptr, who owns this object, and can this address outlive the object? If the answer is unclear, prefer a reference or a normal value.
Prompt:
Refactor this C++ function to avoid unsafe raw pointers where possible.
For every reference or pointer you use, explain whether it can be null and who owns the object.Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done