In programming, particularly in Python and other object-oriented languages, the concepts of shallow copy and deep copy are essential for managing and duplicating objects.
A shallow copy creates a new object that is a copy of the original object, but it only copies the reference pointers to the nested objects within the original. So, if you modify a nested object within the shallow copy, that change will also reflect in the original object.
A deep copy, on the other hand, creates a new object and recursively copies all objects found within the original, including all nested objects. Changes made to a deep copy do not affect the original object.
Here’s an example in PHP:
<?php
class Person {
public $name;
public $friends;
public function __construct($name, $friends) {
$this->name = $name;
$this->friends = $friends;
}
}
// Original object
$alice = new Person("Alice", ["Bob", "Charlie"]);
// Shallow copy
$shallowCopy = $alice; // Both point to the same instance
// Deep copy
$deepCopy = new Person($alice->name, $alice->friends); // Creates a new instance
$deepCopy->friends = array_merge([], $deepCopy->friends); // Ensures separate friends array
// Modify the shallow copy
$shallowCopy->name = "Alicia";
$shallowCopy->friends[0] = "Bobby"; // This will affect $alice as well
echo "Alice's name: " . $alice->name . "<br>";
echo "Shallow Copy's name: " . $shallowCopy->name . "<br>";
// Modify deep copy
$deepCopy->name = "Alison";
$deepCopy->friends[0] = "Diana"; // This won't affect $alice
echo "Alice's name: " . $alice->name . "<br>";
echo "Deep Copy's name: " . $deepCopy->name . "<br>";
?>
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?