ece150: add constructors

This commit is contained in:
eggy 2022-11-24 17:35:58 -05:00
parent b537a530c8
commit b59c7ada6c

View File

@ -557,3 +557,38 @@ The following are all exception classes in `std`:
} catch (...) { } 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.