Value semantics and reference semantics are two fundamental concepts in programming that describe how data is accessed and manipulated. Understanding these concepts is crucial when designing software and managing memory efficiently.
Value semantics means that when a variable is assigned to another variable, a copy of the value is made. Each variable holds its own copy of the data, independent of others. Changes made to one variable do not affect the other.
Reference semantics, on the other hand, implies that when a variable is assigned to another, both variables point to the same memory location. Modifying the data through one variable will reflect in the other, as they share the same reference.
The following example illustrates the difference between value semantics and reference semantics:
// Value Semantics
$a = 10;
$b = $a; // $b copies the value of $a
$b = 20; // Changing $b does not affect $a
echo "Value Semantics: a = $a, b = $b"; // Output: a = 10, b = 20
// Reference Semantics
$c = [1, 2, 3];
$d = &$c; // $d references the same array as $c
$d[0] = 100; // Changing $d will affect $c
echo "Reference Semantics: c[0] = {$c[0]}, d[0] = {$d[0]}"; // Output: c[0] = 100, d[0] = 100
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?