The Big Three Rule

When creating a value object, it is therefore essential that you follow the rule of “ The Big Three.” 

This term was introduced by Marshall Cline in the early nineties and essentially states that there are three member functions that always go together: the destructor, the copy constructor, and the assignment operator

If you define one of these, you normally need to define the other two as well.
 (Note: Declaring an empty virtual destructor  to enable subclassing is one exception, as it does not perform any actual deallocation).

Copy constructor. 
A copy constructor is a special constructor that creates a new object from an existing object. If you do not define a copy constructor, the compiler will generate one for you that performs a shallow copy of the existing object's member variables. So if your object allocates any resources, you most likely need a copy constructor so that you can perform a deep
copy. 
The copy constructor gets called in the following situations:
• An object is passed to a method by value or returned by value
• An object is initialized using the syntax, MyClass a = b;
• An object is placed in a brace-enclosed initializer list
• An object is thrown or caught in an exception

Assignment operator. 
The assignment operator is used to assign the value of one object to another object, for example, a = b. It differs from the copy constructor in that the object being assigned to already exists. 
Some guidelines for implementing the assignment operator include:
1. Use a const reference for the right-hand operand.
2. Return *this as a reference to allow operator chaining.
3. Destroy any existing state before setting the new state.
4. Check for self-assignment (a = a) by comparing this to &rhs.

Destructor. 
The destructor is called in response to a delete call in order to release any resources that the object is holding. There can be only one destructor for a class. If you do not specify a destructor, your C++ compiler will generate one automatically. 
The compiler will also generate code to automatically call the destructors for all of your member variables, in the reverse order they appear in the class declaration.

Tips 1:
If your class allocates resources, you should follow the rule of The Big Three and define a destructor, copy
constructor, and assignment operator.

Tips 2:
To prevent copies, a class must explicitly declare its copy constructor as private or use boost::noncopyable.

Tip 3:

Always prefer passing a non-mutable object as a const reference rather than passing it by value. This will avoid the memory and performance costs to create and destroy a temporary copy of the object and all of its member and inherited objects.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值