Rule of three (C++ programming)
From Wikipedia, the free encyclopedia
The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class or struct defines one of the following it should probably explicitly define all three[1]:
These three methods are special member functions that are automatically created by the compiler if they are not explicitly declared by the programmer. If one of these had to be defined by the programmer, it means that the compiler-generated version does not fit the needs of the class in one case and it will probably not fit in the other cases either.
An amendment to this rule is that if Resource Acquisition Is Initialization (RAII) is used the destructor may be left undefined (also known as The Law of The Big Two[2].
Because implicitly-generated constructors and assignment operators simply copy all class data members[3], defining explicit copy constructors and copy assignment operators is needed in cases where the class encapsulates complex data structures or could hold exclusive access to resources.
[edit] References
- ^ Stroustrup, Bjarne (2000). The C++ Programming Language, 3, Addison-Wesley, 283-4. ISBN 978-0201700732.
- ^ Karlsson, Bjorn; Wilson, Matthew (2004-10-01). The Law of the Big Two. The C++ Source. Artima. Retrieved on 2008-01-22.
- ^ The C++ Programming Language, 271.