C++ 三/五/零法则(Rule of Three/Five/Zero)
C++ 三/五/零 法则是关于资源管理类设计的核心原则,指导开发者如何正确处理类中的特殊成员函数。
规则演变
1. 三法则(C++98/03)
定义:如果一个类需要自定义以下任何一个,那么它通常需要全部三个:
- 析构函数(
~T()) - 拷贝构造函数(
T(const T&)) - 拷贝赋值运算符(
T& operator=(const T&))
适用场景:当类管理独占资源(如动态内存、文件句柄等)时。
示例:
class RuleOfThree {
int* data;
public:
RuleOfThree(int size) : data(new int[size]) {
}
~RuleOfThree() {
delete[] data; } // 1. 需要析构
// 2. 需要拷贝构造
RuleOfThree(const RuleOfThree& other) : data(new int[/*size*/]) {
std::copy(other.data, other.data + /*size*/, data);
}
// 3. 需要拷贝赋值
RuleOfThree& operator=(const RuleOfThree& other) {
if (this != &other) {
delete[] data;
data = new int[/*size*/];
std::copy(other.data, other.data + /*size*/, data

最低0.47元/天 解锁文章
890

被折叠的 条评论
为什么被折叠?



