Rule of three (C++ programming)
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 defines one of the following it should probably explicitly define all three[1]:
These three functions 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. The term "Rule of three" was coined by Marshall Cline in 1991.[2]
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[3]).
Because implicitly-generated constructors and assignment operators simply copy all class data members[4], one should define explicit copy constructors and copy assignment operators for classes that encapsulate complex data structures or have external references such as pointers, since only the pointer gets copied, not the object it points to.
References
- ↑ Stroustrup, Bjarne (2000). The C++ Programming Language (3 ed.). Addison-Wesley. pp. 283–4. ISBN 978-0201700732.
- ↑ Koenig, Andrew; Barbara E. Moo (2001-06-01). "C++ Made Easier: The Rule of Three". Dr. Dobb's Journal. http://www.ddj.com/cpp/184401400. Retrieved 2009-09-08.
- ↑ Karlsson, Bjorn; Wilson, Matthew (2004-10-01). "The Law of the Big Two". The C++ Source. Artima. http://www.artima.com/cppsource/bigtwo.html. Retrieved 2008-01-22.
- ↑ The C++ Programming Language. p. 271.
Stub icon | This computer science article is a stub. You can help Wikipedia by expanding it. |
de:Dreierregel (C++) ru:Правило трёх (C++ программирование) uk:Правило трьох (C++) zh:三法則 (C++程式設計)
If you like SEOmastering Site, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...