|
1 | 1 | # Introduction
|
2 | 2 |
|
| 3 | +## The `auto` Keyword in C++ |
| 4 | + |
| 5 | +In C++, the `auto` keyword is a powerful feature introduced in C++11, used to declare variables with an inferred data type. |
| 6 | +The compiler deduces the type of the variable based on its initializer, which can make code more readable and easier to maintain. |
| 7 | + |
| 8 | +## Example Usage |
| 9 | + |
| 10 | +Consider the following example where `auto` is used to declare variables: |
| 11 | + |
| 12 | +```cpp |
| 13 | +auto dragon_population{3}; // dragon_population is deduced as an integer |
| 14 | +auto westeros{7.7777}; // westeros is deduced as a double |
| 15 | +auto wedding_location{"The Twins"}; // wedding_location is deduced as a const char*, not std::string |
| 16 | +``` |
| 17 | +
|
| 18 | +In each case, the type of the variable is inferred from the value it is initialized with. |
| 19 | +
|
| 20 | +## Type Inference |
| 21 | +
|
| 22 | +The `auto` keyword helps by writing more concise and readable code by reducing the verbosity of explicit types. |
| 23 | +
|
| 24 | +```cpp |
| 25 | +const std::vector<std::string> pigeon_pie{"flour", "butter", "pigeon", "salt"}; |
| 26 | +auto purple_wedding_pie{pigeon_pie}; |
| 27 | +purple_wedding_pie.emplace_back("the strangler"); |
| 28 | +``` |
| 29 | + |
| 30 | +In this loop, `auto` deduces the type of `purple_wedding_pie` as `std::vector<std::string>`, avoiding the need to explicitly specify the type again. |
| 31 | + |
| 32 | +## Compatibility |
| 33 | + |
| 34 | +The `auto` keyword is compatible with various C++ constructs making it a versatile tool in modern C++ programming. |
| 35 | + |
| 36 | +```cpp |
| 37 | +auto& element{array[0]}; // reference to an element |
| 38 | +const auto object{otherObject}; // const type version of otherObject's type |
| 39 | +auto* ptr{&x}; // pointer to x with the same type as x, but as a pointer. |
| 40 | +``` |
| 41 | +
|
| 42 | +In later concept we will often see the `auto` keyword with lambda expressions, range-based for-loops, and iterators. |
| 43 | +
|
| 44 | +## Smart Pointers |
| 45 | +
|
3 | 46 | Smart pointers are a modern C++ feature designed to provide automatic memory management, helping to prevent memory leaks and dangling pointers commonly associated with raw pointers.
|
4 | 47 | They act as wrappers around raw pointers, adding additional functionality such as automatic memory deallocation when the pointer is no longer needed.
|
5 | 48 |
|
|
0 commit comments