Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
206 字
1 分钟
Value, Reference, Pointer and Memory

1. Difference Between Value Way and Reference Way (Defining Variable/Object)#

Value Way (Pass / Define by Value)#

int a = 10;
MyClass obj;

Characteristics

  • A new copy of the variable/object is created
  • Changes do not affect the original
  • Object lifetime is independent
  • May be expensive for large objects

Reference Way (Define by Reference)#

int& ref = a;
MyClass& refObj = obj;

Characteristics

  • No new object is created
  • Reference is an alias to an existing object
  • Changes affect the original
  • Must be initialized
  • Cannot be null or rebound

Value vs Reference Summary#

AspectValueReference
Copy createdYesNo
Memory costHigherLower
Modification affects originalNoYes
Can be nullNoNo
RebindingN/ANo

2. Advantages and Disadvantages of Using a Pointer#

Advantages#

  • Can represent optional / null objects
  • Supports dynamic memory allocation
  • Enables polymorphism
  • Allows pointer arithmetic
  • Can change what it points to

Disadvantages#

  • Risk of memory leaks
  • Risk of dangling pointers
  • Risk of null pointer dereference
  • Harder to read and maintain
  • Manual memory management required (unless smart pointers used)

Pointer Usage Summary#

AspectPointer
Can be nullYes
Safer than reference
Flexible
Error-prone

3. Difference Between Manual Memory Management in C and C++#

Memory Allocation & Release in C#

OperationFunction
Allocatemalloc(), calloc()
Deallocatefree()
Object construction❌ Not supported
Type safety❌ No
int* p = (int*)malloc(sizeof(int));
free(p);

Memory Allocation & Release in C++#

OperationOperator
Allocatenew, new[]
Deallocatedelete, delete[]
Constructor call✅ Yes
Destructor call✅ Yes
Type safety✅ Yes
int* p = new int(10);
delete p;

Key Differences (Exam Favorite)#

FeatureCC++
Memory functionsmalloc/freenew/delete
Constructor called
Destructor called
Type safe
Overloading support

One-Line Exam Summary#

  • Value way creates a copy; reference way creates an alias.
  • Pointers are powerful but error-prone.
  • C uses malloc/free; C++ uses new/delete with object lifetime management.
Value, Reference, Pointer and Memory
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/value-reference-pointer-memory/
作者
🐦‍🔥不死鸟Anka
发布于
2025-12-15
许可协议
MIT

部分信息可能已经过时

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