Giao diện tối
21.13 — Shallow vs. deep copying
🎯 Mục Tiêu Bài Học
- Nắm vững bản chất lý thuyết và cơ chế hoạt động của Shallow vs. deep copying trong tiêu chuẩn ISO C++.
- Hiểu rõ cách máy tính tổ chức bộ nhớ (RAM, CPU registers) khi thực thi mã nguồn liên quan.
- Nhận biết các cạm bẫy lỗi kinh điển (Undefined Behavior, Memory Leak, Bug logic) và cách phòng tránh.
- Áp dụng các quy tắc thực hành tốt nhất (Best Practices) chuẩn công nghiệp và cập nhật C++20/C++23 hiện đại.
21.13 — Shallow vs. deep copying
Shallow copying
Because C++ does not know much about your class, the default copy hàm tạo (constructor) and default phép gán các toán tử it provides use a copying method known as a memberwise copy (also known as a shallow copy). This means that C++ copies each member of the class individually (using the phép gán toán tử for overloaded toán tử=, and direct sự khởi tạo for the copy hàm tạo (constructor)). When classes are simple (e.g. do not contain any dynamically allocated memory), this works very well.
For example, let’s take a look at our Fraction class:
cpp
#include <cassert>
#include <iostream>
class Fraction
{
private:
int m_numerator { 0 };
int m_denominator { 1 };
public:
// Default constructor
Fraction(int numerator = 0, int denominator = 1)
: m_numerator{ numerator }
, m_denominator{ denominator }
{
assert(denominator != 0);
}
friend std::ostream& operator<<(std::ostream& out, const Fraction& f1);
};
std::ostream& operator<<(std::ostream& out, const Fraction& f1)
{
out << f1.m_numerator << '/' << f1.m_denominator;
return out;
}The default copy hàm tạo (constructor) and default phép gán toán tử provided by the trình biên dịch for this class look something like this:
cpp
#include <cassert>
#include <iostream>
class Fraction
{
private:
int m_numerator { 0 };
int m_denominator { 1 };
public:
// Default constructor
Fraction(int numerator = 0, int denominator = 1)
: m_numerator{ numerator }
, m_denominator{ denominator }
{
assert(denominator != 0);
}
// Possible implementation of implicit copy constructor
Fraction(const Fraction& f)
: m_numerator{ f.m_numerator }
, m_denominator{ f.m_denominator }
{
}
// Possible implementation of implicit assignment operator
Fraction& operator= (const Fraction& fraction)
{
// self-assignment guard
if (this == &fraction)
return *this;
// do the copy
m_numerator = fraction.m_numerator;
m_denominator = fraction.m_denominator;
// return the existing object so we can chain this operator
return *this;
}
friend std::ostream& operator<<(std::ostream& out, const Fraction& f1)
{
out << f1.m_numerator << '/' << f1.m_denominator;
return out;
}
};Note that because these default versions work just fine for copying this class, there’s really no reason to write our own version of these các hàm in this case.
However, when designing classes that handle dynamically allocated memory, memberwise (shallow) copying can get us in a lot of trouble! This is because shallow copies of a con trỏ just copy the address of the con trỏ -- it does not allocate any memory or copy the contents being pointed to!
Let’s take a look at an example of this:
cpp
#include <cstring> // for strlen()
#include <cassert> // for assert()
class MyString
{
private:
char* m_data{};
int m_length{};
public:
MyString(const char* source = "" )
{
assert(source); // make sure source isn't a null string
// Find the length of the string
// Plus one character for a terminator
m_length = std::strlen(source) + 1;
// Allocate a buffer equal to this length
m_data = new char[m_length];
// Copy the parameter string into our internal buffer
for (int i{ 0 }; i < m_length; ++i)
m_data[i] = source[i];
}
~MyString() // destructor
{
// We need to deallocate our string
delete[] m_data;
}
char* getString() { return m_data; }
int getLength() { return m_length; }
};The above is a simple string class that allocates memory to hold a string that we pass in. Note that we have not defined a copy hàm tạo (constructor) or overloaded phép gán toán tử. Consequently, C++ will provide a default copy hàm tạo (constructor) and default phép gán toán tử that do a shallow copy. The copy hàm tạo (constructor) will look something like this:
cpp
MyString::MyString(const MyString& source)
: m_length { source.m_length }
, m_data { source.m_data }
{
}Note that m_data is just a shallow con trỏ copy of source.m_data, meaning they now both point to the same thing.
Now, consider the following snippet of code:
cpp
#include <iostream>
int main()
{
MyString hello{ "Hello, world!" };
{
MyString copy{ hello }; // use default copy constructor
} // copy is a local variable, so it gets destroyed here. The destructor deletes copy's string, which leaves hello with a dangling pointer
std::cout << hello.getString() << '\n'; // this will have undefined behavior
return 0;
}While this code looks harmless enough, it contains an insidious problem that will cause the program to exhibit hành vi không xác định (Hành vi không xác định (Undefined Behavior - UB) - UB)!
Let’s break down this example line by line:
cpp
MyString hello{ "Hello, world!" };This line is harmless enough. This calls the MyString hàm tạo (constructor), which allocates some memory, sets hello.m_data to point to it, and then copies the string “Hello, world!” into it.
cpp
MyString copy{ hello }; // use default copy constructorThis line seems harmless enough as well, but it’s actually the source of our problem! When this line is evaluated, C++ will use the default copy hàm tạo (constructor) (because we haven’t provided our own). This copy hàm tạo (constructor) will do a shallow copy, initializing copy.m_data to the same address of hello.m_data. As a result, copy.m_data and hello.m_data are now both pointing to the same piece of memory!
cpp
} // copy gets destroyed hereWhen copy goes out of phạm vi truy cập (scope), the MyString hàm hủy (destructor) is called on copy. The hàm hủy (destructor) deletes the dynamically allocated memory that both copy.m_data and hello.m_data are pointing to! Consequently, by deleting copy, we’ve also (inadvertently) affected hello. Variable copy then gets destroyed, but hello.m_data is left pointing to the deleted (invalid) memory!
cpp
std::cout << hello.getString() << '\n'; // this will have undefined behaviorNow you can see why this program has hành vi không xác định (Hành vi không xác định (Undefined Behavior - UB) - UB). We deleted the string that hello was pointing to, and now we are trying to print the value of memory that is no longer allocated.
The root of this problem is the shallow copy done by the copy hàm tạo (constructor) -- doing a shallow copy on con trỏ values in a copy hàm tạo (constructor) or overloaded phép gán toán tử is almost always asking for trouble.
Deep copying
One answer to this problem is to do a deep copy on any non-null các con trỏ being copied. A deep copy allocates memory for the copy and then copies the actual value, so that the copy lives in distinct memory from the source. This way, the copy and source are distinct and will not affect each other in any way. Doing deep copies requires that we write our own copy các hàm tạo (constructors) and overloaded phép gán các toán tử.
Let’s go ahead and show how this is done for our MyString class:
cpp
// assumes m_data is initialized
void MyString::deepCopy(const MyString& source)
{
// first we need to deallocate any value that this string is holding!
delete[] m_data;
// because m_length is not a pointer, we can shallow copy it
m_length = source.m_length;
// m_data is a pointer, so we need to deep copy it if it is non-null
if (source.m_data)
{
// allocate memory for our copy
m_data = new char[m_length];
// do the copy
for (int i{ 0 }; i < m_length; ++i)
m_data[i] = source.m_data[i];
}
else
m_data = nullptr;
}
// Copy constructor
MyString::MyString(const MyString& source)
{
deepCopy(source);
}As you can see, this is quite a bit more involved than a simple shallow copy! First, we have to check to make sure source even has a string (line 11). If it does, then we allocate enough memory to hold a copy of that string (line 14). Finally, we have to manually copy the string (lines 17 and 18).
Now let’s do the overloaded phép gán toán tử. The overloaded phép gán toán tử is slightly trickier:
cpp
// Assignment operator
MyString& MyString::operator=(const MyString& source)
{
// check for self-assignment
if (this != &source)
{
// now do the deep copy
deepCopy(source);
}
return *this;
}Note that our phép gán toán tử is very similar to our copy hàm tạo (constructor), but there are three major differences:
<li> We added a self-phép gán check. <li> We return *this so we can chain the phép gán toán tử. <li> We need to explicitly deallocate any value that the string is already holding (so we don’t have a rò rỉ bộ nhớ (memory leak) when m_data is reallocated later). This is handled inside deepCopy().
When the overloaded phép gán toán tử is called, the item being assigned to may already contain a previous value, which we need to make sure we clean up before we assign memory for new values. For non-dynamically allocated các biến (which are a fixed size), we don’t have to bother because the new value just overwrites the old one. However, for dynamically allocated các biến, we need to explicitly deallocate any old memory before we allocate any new memory. If we don’t, the code will not crash, but we will have a rò rỉ bộ nhớ (memory leak) that will eat away our free memory every time we do an phép gán!
The rule of three
Remember the rule of three? If a class requires a user-defined hàm hủy (destructor), copy hàm tạo (constructor), or copy phép gán toán tử, then it probably requires all three. This is why. If we’re user-defining any of these các hàm, it’s probably because we’re dealing with dynamic memory allocation. We need the copy hàm tạo (constructor) and copy phép gán to handle deep copies, and the hàm hủy (destructor) to deallocate memory.
A better solution
Classes in the standard library that deal with dynamic memory, such as std::string and std::vector, handle all of their memory management, and have overloaded copy các hàm tạo (constructors) and phép gán các toán tử that do proper deep copying. So instead of doing your own memory management, you can just khởi tạo or assign them like normal fundamental các biến! That makes these classes simpler to use, less error-prone, and you don’t have to spend time writing your own overloaded các hàm!
Tổng kết bài học
<li>The default copy hàm tạo (constructor) and default phép gán các toán tử do shallow copies, which is fine for classes that contain no dynamically allocated các biến. <li>Classes with dynamically allocated các biến need to have a copy hàm tạo (constructor) and phép gán toán tử that do a deep copy. <li>Favor using classes in the standard library over doing your own memory management.
💡 Tóm Tắt Quy Tắc Vàng (Core Guidelines)
- Luôn hiểu rõ vòng đời và quyền sở hữu (Ownership) của dữ liệu trước khi viết code.
- Ưu tiên khởi tạo đồng nhất với dấu ngoặc nhọn
{}để ngăn chặn lỗi thu hẹp kiểu dữ liệu (Narrowing conversions). - Bật toàn bộ cờ cảnh báo
-Wall -Wextra -Wpedanticđể compiler giúp bạn phát hiện bug từ sớm!