Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
373 字
2 分钟
Reference and Pointer

Reference vs Pointer#

AspectReferencePointer
DefinitionAn alias (another name) for an existing variableA variable that stores the address of another variable
InitializationMust be initialized when declaredCan be declared without initialization
Null valueCannot be nullCan be null (nullptr / NULL)
ReassignmentCannot be changed to refer to another objectCan point to a different object
Syntax usageUsed directly like a normal variableRequires dereferencing (*) to access the value
MemoryDoes not require separate memoryRequires its own memory to store an address
SafetySafer, fewer chances of misuseLess safe, can cause dangling or null pointer issues
ArithmeticNot allowedPointer arithmetic is allowed
Use caseWhen you always refer to the same objectWhen you need optional references or dynamic allocation

Simple Example#

int x = 10;
int& ref = x; // reference
int* ptr = &x; // pointer
ref = 20; // x becomes 20
*ptr = 30; // x becomes 30

One-Line Summary (Exam-Friendly)#

  • A reference is a constant alias to a variable and cannot be null or reassigned.
  • A pointer stores a memory address, can be null, and can be reassigned.

When to Use a Reference Parameter#

1. To modify the original argument#

  • Changes inside the function affect the caller’s variable.
void increment(int& x) {
x++;
}

📌 Use a reference when the parameter must exist and must not be null.


2. To avoid copying large objects#

  • More efficient than pass-by-value.
void print(const string& s) {
cout << s;
}

📌 Use a const reference when you don’t want to modify the object.


3. When the object should not change identity#

  • The function should always refer to the same object.

When to Use a Pointer Parameter#

1. When the parameter can be optional (nullable)#

  • A pointer can be nullptr, a reference cannot.
void print(int* p) {
if (p != nullptr)
cout << *p;
}

2. When the function needs to work with arrays or dynamic memory#

  • Common in low-level code.
void fillArray(int* arr, int size) {
for (int i = 0; i < size; i++)
arr[i] = i;
}

3. When you need to change what the pointer points to#

  • (e.g., allocate or redirect memory)
void allocate(int*& p) {
p = new int(10);
}

Reference vs Pointer (Decision Guide)#

SituationUse ReferenceUse Pointer
Must not be null
Optional parameter
Avoid copying
Modify original object
Change what is referenced
Safer & cleaner code

Short Exam Answer#

  • Use a reference when the parameter must always refer to a valid object and you want safer, cleaner syntax.
  • Use a pointer when the parameter can be null, optional, or needs to be reassigned.
Reference and Pointer
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/reference-and-pointer/
作者
🐦‍🔥不死鸟Anka
发布于
2025-12-15
许可协议
MIT

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00