From b59c7ada6c1696a2b4fc5f8c3f67a5cf4eb466ca Mon Sep 17 00:00:00 2001 From: eggy Date: Thu, 24 Nov 2022 17:35:58 -0500 Subject: [PATCH] ece150: add constructors --- docs/ce1/ece150.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 5d35c3d..3756dac 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -557,3 +557,38 @@ The following are all exception classes in `std`: } catch (...) { } ``` + +## Copies and moves + +The copy constructor by default copies **the value** of every public and private field, including pointers, both from field initialisation or assignment. + +```cpp +MyClass n{}; +MyClass m{n}; // copy +MyClass p = n; // copy +``` + +The move constructor copies every field from the other object and resets the original object to no longer point to that data, typically called only via `std::move`. + +```cpp +MyClass a{}; +MyClass b{std::move(a)}; +``` + +It is an excellent idea to blank out the two constructors to do nothing so that unexpected behaviour does not occur. + +```cpp +class MyClass { + public: + MyClass(MyClass const &rhs) = delete; + MyClass(MyClass &&rhs) = delete; + MyClass &operator=(MyClass const &rhs) = delete; + MyClass &operator=(MyClass &&rhs) = delete; +} +``` + +If a move occurs and the compiler determines that the original object is no longer needed, its destructor is automatically called immediately after the constructor / assignment finishes. + +During construction, default initialisation picks the one with the fewest parameters if ambiguous. Parameters passed by value are **copied** by reference via the copy constructor. + +Much like statically allocated arrays, dynamically allocated arrays also automatically dereference when accessed by index.