From ba5323b28f89677f5dc6c3aef7cc232846fb1629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Thu, 20 Jan 2022 17:33:21 +0100 Subject: [PATCH 1/9] module 1 structure unified --- module1/{00_intro.md => 00-intro.md} | 3 +- module1/00_coffee_break.md | 10 ----- module1/00_lunch_break.md | 10 ----- module1/{pretest.md => 01-pretest.md} | 0 module1/{standards.md => 02-standards.md} | 29 +++++++++----- .../{static_assert.md => 03-static-assert.md} | 2 +- module1/{nullptr.md => 04-nullptr.md} | 0 module1/{scoped_enum.md => 05-scoped-enum.md} | 0 module1/{auto.md => 06-auto.md} | 6 --- module1/{using.md => 07-using.md} | 4 +- ...zation.md => 08-uniform-initialization.md} | 0 ...md => 09-default-delete-final-override.md} | 34 +++++++++-------- module1/10-recap.md | 15 ++++++++ ...etest_answers.md => 11-pretest-answers.md} | 24 ------------ module1/{decltype.md => 12-decltype.md} | 5 +++ module1/index.html | 38 ++++++++----------- module1/recap.md | 20 ---------- 17 files changed, 78 insertions(+), 122 deletions(-) rename module1/{00_intro.md => 00-intro.md} (94%) delete mode 100644 module1/00_coffee_break.md delete mode 100644 module1/00_lunch_break.md rename module1/{pretest.md => 01-pretest.md} (100%) rename module1/{standards.md => 02-standards.md} (63%) rename module1/{static_assert.md => 03-static-assert.md} (93%) rename module1/{nullptr.md => 04-nullptr.md} (100%) rename module1/{scoped_enum.md => 05-scoped-enum.md} (100%) rename module1/{auto.md => 06-auto.md} (95%) rename module1/{using.md => 07-using.md} (97%) rename module1/{uniform_initialization.md => 08-uniform-initialization.md} (100%) rename module1/{default_delete_final_override.md => 09-default-delete-final-override.md} (79%) create mode 100644 module1/10-recap.md rename module1/{pretest_answers.md => 11-pretest-answers.md} (78%) rename module1/{decltype.md => 12-decltype.md} (93%) delete mode 100644 module1/recap.md diff --git a/module1/00_intro.md b/module1/00-intro.md similarity index 94% rename from module1/00_intro.md rename to module1/00-intro.md index a22c7db..b21ce84 100644 --- a/module1/00_intro.md +++ b/module1/00-intro.md @@ -5,7 +5,7 @@ * Your hobbies ___ - +

Łukasz ZiobroΕ„

@@ -68,6 +68,7 @@ ___ Note: Vegas rule: What happens in Vegas, it stays in Vegas. If you want to complain about the employer, I won't tell anyone + ___ diff --git a/module1/00_coffee_break.md b/module1/00_coffee_break.md deleted file mode 100644 index 9d6de6f..0000000 --- a/module1/00_coffee_break.md +++ /dev/null @@ -1,10 +0,0 @@ - -# Break - -# ☕ - -___ - -## Recap - -### What were we talking about before the break? \ No newline at end of file diff --git a/module1/00_lunch_break.md b/module1/00_lunch_break.md deleted file mode 100644 index 4161c92..0000000 --- a/module1/00_lunch_break.md +++ /dev/null @@ -1,10 +0,0 @@ - -# Lunch break - -# 🍝 - -___ - -## Recap - -### What were we talking about before the break? \ No newline at end of file diff --git a/module1/pretest.md b/module1/01-pretest.md similarity index 100% rename from module1/pretest.md rename to module1/01-pretest.md diff --git a/module1/standards.md b/module1/02-standards.md similarity index 63% rename from module1/standards.md rename to module1/02-standards.md index c0c14da..fd9e406 100644 --- a/module1/standards.md +++ b/module1/02-standards.md @@ -18,7 +18,8 @@ ___ * 2013 - full version of C++1y draft * 2014 - C++1y published as C++14 * 2017 - C++1z published as C++17 -* 2020 - C++2a should be published as C++20 +* 2020 - C++2a published as C++20 +* 2023 - C++2b should be published as C++23 ___ @@ -26,32 +27,40 @@ ___ ### [GCC](https://gcc.gnu.org/projects/cxx-status.html) - [Clang](https://clang.llvm.org/cxx_status.html) -
-

C++20

+
+

C++23

  • Full support: not implemented yet
  • -
  • Compiler flags: -std=c++2a
  • +
  • Compiler flags: -std=c++2b
  • +
+
+ +
+

C++20

+
    +
  • (almost) full support: gcc11, clang14
  • +
  • Compiler flags: -std=c++20, -std=c++2a
-
+

C++17

  • Full support: gcc7, clang5
  • -
  • Compiler flags: -std=c++17, -std=c++1z
  • +
  • Compiler flags: -std=c++17, -std=c++1z
-
+

C++14

  • Full support: gcc5, clang3.4
  • -
  • Compiler flags: -std=c++14, -std=c++1y
  • +
  • Compiler flags: -std=c++14, -std=c++1y
  • Enabled by default since gcc6.1
-
+

C++11

  • Full support: gcc4.8.1, clang3.3
  • -
  • Compiler flags: -std=c++11, -std=c++0x
  • +
  • Compiler flags: -std=c++11, -std=c++0x
diff --git a/module1/static_assert.md b/module1/03-static-assert.md similarity index 93% rename from module1/static_assert.md rename to module1/03-static-assert.md index 745cd76..3d12adb 100644 --- a/module1/static_assert.md +++ b/module1/03-static-assert.md @@ -26,7 +26,7 @@ void swap(T& a, T& b) Performs compile-time assertion checking. Usually used with `` library. -The message is optional from C++17. +The message provided as a second parameter is optional from C++17. ___ diff --git a/module1/nullptr.md b/module1/04-nullptr.md similarity index 100% rename from module1/nullptr.md rename to module1/04-nullptr.md diff --git a/module1/scoped_enum.md b/module1/05-scoped-enum.md similarity index 100% rename from module1/scoped_enum.md rename to module1/05-scoped-enum.md diff --git a/module1/auto.md b/module1/06-auto.md similarity index 95% rename from module1/auto.md rename to module1/06-auto.md index 5b579f5..40d9299 100644 --- a/module1/auto.md +++ b/module1/06-auto.md @@ -156,9 +156,3 @@ ___ Put auto wherever you think is good. Use range-based for loops wherever possible. - -### Let's have some fun :) - - -Connect to my VSC and edit my program simultaneously. - diff --git a/module1/using.md b/module1/07-using.md similarity index 97% rename from module1/using.md rename to module1/07-using.md index c138310..0ca72df 100644 --- a/module1/using.md +++ b/module1/07-using.md @@ -22,7 +22,7 @@ using SocketContainer = std::vector>; **Rationale**: More intuitive alias creation. -A type alias is a name that refers to a previously defined type. It could be created with typedef. +A type alias is a name that refers to a previously defined type. It could be created with `typedef`. From C++11 type aliases should be created with `using` keyword. @@ -37,7 +37,7 @@ using StrKeyMap = std::map; StrKeyMap my_map; // std::map ``` -Type alias can be parametrized with templates. It was impossible with typedef. +Type alias can be parametrized with templates. It was impossible with `typedef`. Template aliases cannot be specialized. diff --git a/module1/uniform_initialization.md b/module1/08-uniform-initialization.md similarity index 100% rename from module1/uniform_initialization.md rename to module1/08-uniform-initialization.md diff --git a/module1/default_delete_final_override.md b/module1/09-default-delete-final-override.md similarity index 79% rename from module1/default_delete_final_override.md rename to module1/09-default-delete-final-override.md index 68d2cfd..44368af 100644 --- a/module1/default_delete_final_override.md +++ b/module1/09-default-delete-final-override.md @@ -26,7 +26,7 @@ ___ ## `default` keyword * default declaration enforces a compiler to generate default implicit implementation for marked functions -* 6 special functions can be marked as default: +* 7 special functions can be marked as default: * default c-tor * copy c-tor * copy assignment operator @@ -127,37 +127,41 @@ struct B : A { ___ + ## `override` keyword -

+```cpp
 struct Base {
     virtual void a();
     virtual void b() const;
     virtual void c();
     void d();
 };
-
+``` -

+```cpp
 struct WithoutOverride : Base {
-    void a(); // overrides Base::a()
-    void b(); // doesn't override B::b() const
-    virtual void c(); // overrides B::c()
-    void d(); // doesn't override B::d()
+    void a();         // overrides Base::a()
+    void b();         // doesn't override B::b() const
+    virtual void c(); // overrides B::c()
+    void d();         // doesn't override B::d()
 };
-
+``` + -

+```cpp
 struct WithOverride : Base {
-    void a() override; // OK - overrides Base::a()
-    void b() override; // error - doesn't override B::b() const
+    void a() override;         // OK - overrides Base::a()
+    void b() override;         // error - doesn't override B::b() const
     virtual void c() override; // OK - overrides B::c(char)
-    void d() override; // error - B::d() is not virtual
+    void d() override;         // error - B::d() is not virtual
 };
-
+``` + -

override declaration enforces a compiler to check, if given virtual function is declared in the same way in a base class.

+override declaration enforces a compiler to check, if given virtual function is declared in the same way in a base class. + ___ diff --git a/module1/10-recap.md b/module1/10-recap.md new file mode 100644 index 0000000..2e8a7ad --- /dev/null +++ b/module1/10-recap.md @@ -0,0 +1,15 @@ + +# Recap + +___ + + +## What do you remember from today's session? + +1. static_assert +2. nullptr +3. scoped enums +4. auto keyword and range-based for loop +5. using alias +6. uniform initialization +7. new keywords: default, delete, final, override diff --git a/module1/pretest_answers.md b/module1/11-pretest-answers.md similarity index 78% rename from module1/pretest_answers.md rename to module1/11-pretest-answers.md index e98dd94..09a8522 100644 --- a/module1/pretest_answers.md +++ b/module1/11-pretest-answers.md @@ -47,27 +47,3 @@ ___ 1. free function 1. class method 1. class member object - -___ - -## Post-test - -The link to post-test will be sent to you in a next week. - -It's better to forget some of the content and refresh your knowledge later. - -It enhances knowledge retention :) - -___ - -## Homework - -Take a look into `README.md` file from modern_cpp repository. You can complete all tasks and raise a Pull Request if you wish me to check your homework. - -___ - -## Feedback - -* What could be improved in this training? -* What was the most valuable for you? -* [Training evaluation](https://forms.gle/qEZFvYKdgbxkyxYj7) diff --git a/module1/decltype.md b/module1/12-decltype.md similarity index 93% rename from module1/decltype.md rename to module1/12-decltype.md index 8186d88..68c801a 100644 --- a/module1/decltype.md +++ b/module1/12-decltype.md @@ -1,3 +1,8 @@ + +# `decltype` + +___ + ## `decltype` **Rationale**: Deduction provided in contexts where auto is not allowed. diff --git a/module1/index.html b/module1/index.html index 1728458..26c50b4 100644 --- a/module1/index.html +++ b/module1/index.html @@ -6,7 +6,7 @@ Modern C++ - + @@ -53,63 +53,55 @@

Kamil Szatkowski

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -135,6 +127,6 @@

Thank you πŸ™‚

pdfSeparateFragments: false, plugins: [ RevealMarkdown, RevealHighlight, RevealNotes ] }); - + diff --git a/module1/recap.md b/module1/recap.md deleted file mode 100644 index 8ea36e0..0000000 --- a/module1/recap.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Recap - -___ - - -## What do you remember from today's session? - -1. intro (25’) -2. static_assert (15’) -3. nullptr (10’) -4. scoped enums (30’) -5. β˜•οΈ break (15’) -6. auto keyword and range-based for loop (1h) -7. β˜•οΈ break (10’) -8. using alias (15’) -9. uniform initialization (40’) -10. 🍝 lunch break (50’) -11. new keywords: default, delete, final, override (1h) -12. recap (15’) From 04f2e13ef4884fdedeb5a5ca4641d84cd4c23533 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Wed, 26 Jan 2022 13:15:51 +0100 Subject: [PATCH 2/9] improvements, consteval, constinit added --- module2/{00_intro.md => 00-intro.md} | 2 +- module2/00_coffee_break.md | 4 - module2/00_lunch_break.md | 4 - module2/{pretest.md => 01-pretest.md} | 10 +-- ...ern_cpp_attributes.md => 02-attributes.md} | 20 ++++- ...odern_cpp_constexpr.md => 03-constexpr.md} | 64 ++++++++------ module2/04-consteval-constinit.md | 41 +++++++++ module2/05-noexcept.md | 82 ++++++++++++++++++ module2/{modern_cpp_dsa.md => 06-dsa.md} | 50 ++++++----- ..._bindings.md => 07-structured-bindings.md} | 4 +- .../{modern_cpp_lambda.md => 08-lambda.md} | 84 ++++++++++--------- module2/{modern_cpp_other.md => 09-other.md} | 54 +++++++----- module2/{modern_cpp_recap.md => 10-recap.md} | 0 ...etest_answers.md => 11-pretest-answers.md} | 25 ++---- module2/{index.html => index.en.html} | 53 +++++------- module2/modern_cpp_noexcept.md | 59 ------------- 16 files changed, 318 insertions(+), 238 deletions(-) rename module2/{00_intro.md => 00-intro.md} (96%) delete mode 100644 module2/00_coffee_break.md delete mode 100644 module2/00_lunch_break.md rename module2/{pretest.md => 01-pretest.md} (57%) rename module2/{modern_cpp_attributes.md => 02-attributes.md} (82%) rename module2/{modern_cpp_constexpr.md => 03-constexpr.md} (54%) create mode 100644 module2/04-consteval-constinit.md create mode 100644 module2/05-noexcept.md rename module2/{modern_cpp_dsa.md => 06-dsa.md} (69%) rename module2/{modern_cpp_structure_bindings.md => 07-structured-bindings.md} (92%) rename module2/{modern_cpp_lambda.md => 08-lambda.md} (89%) rename module2/{modern_cpp_other.md => 09-other.md} (71%) rename module2/{modern_cpp_recap.md => 10-recap.md} (100%) rename module2/{pretest_answers.md => 11-pretest-answers.md} (68%) rename module2/{index.html => index.en.html} (67%) delete mode 100644 module2/modern_cpp_noexcept.md diff --git a/module2/00_intro.md b/module2/00-intro.md similarity index 96% rename from module2/00_intro.md rename to module2/00-intro.md index 9efac61..c54653d 100644 --- a/module2/00_intro.md +++ b/module2/00-intro.md @@ -5,7 +5,7 @@ * Your hobbies ___ - +

Łukasz ZiobroΕ„

diff --git a/module2/00_coffee_break.md b/module2/00_coffee_break.md deleted file mode 100644 index 800d78f..0000000 --- a/module2/00_coffee_break.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Break - -# ☕ diff --git a/module2/00_lunch_break.md b/module2/00_lunch_break.md deleted file mode 100644 index 2d2b027..0000000 --- a/module2/00_lunch_break.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Lunch break - -# 🍝 diff --git a/module2/pretest.md b/module2/01-pretest.md similarity index 57% rename from module2/pretest.md rename to module2/01-pretest.md index 8fef0d3..e048f88 100644 --- a/module2/pretest.md +++ b/module2/01-pretest.md @@ -4,14 +4,14 @@ ___ -## Which lambda function is valid? +## Which lambda functions will compile? 1. `[]() -> int { return 4; };` 1. `int [](){ return 4; };` 1. `auto [](){ return 4; };` 1. `[]() -> auto {return 4; };` 1. `[](){ return 4; };` -1. `[] { return 4; }` -1. `[] mutable { return 4; }` -1. `[] -> int { return 4; }` -1. `int []{ return 4; }` +1. `[] { return 4; };` +1. `[] mutable { return 4; };` +1. `[] -> int { return 4; };` +1. `int []{ return 4; };` diff --git a/module2/modern_cpp_attributes.md b/module2/02-attributes.md similarity index 82% rename from module2/modern_cpp_attributes.md rename to module2/02-attributes.md index ab3c284..4cc53a8 100644 --- a/module2/modern_cpp_attributes.md +++ b/module2/02-attributes.md @@ -18,8 +18,8 @@ such as the GNU and IBM language extensions `__attribute__((...))`, Microsoft ex * [[fallthrough]] (C++17) - in switch statement, indicated that fall through is intentional * [[nodiscard]] (C++17) - you cannot ignore value returned from function * [[maybe_unused]] (C++17) - suppress compiler warning on unused class, typedef, variable, function, etc. +* [[likely]], [[unlikely]] (C++20) - optimize for the case where paths of execution more or less likely than any alternative path of execution - ___ ## `[[noreturn]]` attribute @@ -84,7 +84,7 @@ ___ [[maybe_unused]] bool thing2) { [[maybe_unused]] bool b = thing1 && thing2; - assert (b); // in release mode, assert is compiled out, and b is unused + assert(b); // in release mode, assert is compiled out, and b is unused // no warning because it is declared [[maybe_unused]] } // parameters thing1 and thing2 are not used, no warning ``` @@ -112,6 +112,22 @@ old_stuff::legacy(); //Emits warning ___ +## `[[likely]]`, `[[unlikely]]` attributes + +```c++ +constexpr double pow(double x, long long n) noexcept { + if (n > 0) [[likely]] { + return x * pow(x, n - 1); + } else [[unlikely]] { + return 1; + } +} +``` + +___ + ## Exercise Add a new method `double getPi()` in `Circle` class, which returns a PI number. Mark it as deprecated. + +PS. In C++20 you can use `` header. It has mathematical constants defined inside. diff --git a/module2/modern_cpp_constexpr.md b/module2/03-constexpr.md similarity index 54% rename from module2/modern_cpp_constexpr.md rename to module2/03-constexpr.md index 5a6055d..7dbe500 100644 --- a/module2/modern_cpp_constexpr.md +++ b/module2/03-constexpr.md @@ -5,14 +5,17 @@ ___ ## `constexpr` keyword -

Rationale: faster runtime binary by moving some computations at compile-time.

-

constexpr is an expression that can be evaluated at compile time and can appear in constant expressions. We can have:

+**Rationale**: faster runtime binary by moving some computations at compile-time. -* constexpr variable -* constexpr function -* constexpr constructor -* constexpr lambda (default from C++17) -* constexpr if (until C++17) +`constexpr` is an expression that can be evaluated at compile time and can appear in [constant expressions](https://en.cppreference.com/w/cpp/language/constant_expression). We can have: + +* constexpr variables +* constexpr functions + * normal constexpr functions + * constexpr constructors + * constexpr lambdas (default from C++17) + * constexpr destructor (from C++20) +* constexpr if (from C++17) ___ @@ -53,25 +56,28 @@ constexpr int factorial14(int n) { // C++14 } ``` -

constexpr function can be evaluated in both compile time and runtime. Evaluation at compile time can occur when the result is assigned to constexpr variable and arguments can be evaluated at compile time.

+`constexpr` function can be evaluated in both compile time and runtime. Evaluation at compile time must occur when the result is assigned to `constexpr` variable. Arguments must be known at compile time. + ___ -

constexpr functions restrictions

-

In C++11 constexpr functions were very restricted - only 1 return instruction (not returning void). From C++14 the only restrictions are, that function must not:

-
    -
  • contain static or thread_local variables
  • -
  • contain uninitialized variables
  • -
  • call non constexpr function
  • -
  • use non-literal types
  • -
  • be virtual (until C++20)
  • -
  • use asm code blocks (until C++20)
  • -
  • have try-catch block or throw exceptions (until C++20)
  • -
+## `constexpr` functions restrictions + +In C++11 `constexpr` functions were very restricted - only 1 return instruction (not returning void). From C++17 the only restrictions are, that function must not: + +* contain static or thread_local variables +* contain uninitialized variables +* call non constexpr function +* be virtual (until C++20) +* have try-catch block (until C++20) +* be a coroutine (from C++20) + +More info on [cppreference.com](https://en.cppreference.com/w/cpp/language/constexpr). + ___ -

constexpr constructor

+## `constexpr` constructor ```cpp struct Point @@ -87,12 +93,15 @@ struct Point constexpr Point a = { 1, 2 }; ``` -

class Point can be used in constexpr computations, eg in constexpr functions. It is a literal type. Constexpr constructor has the same restrictions as a constexpr function and a class cannot have a virtual base class.

+Class `Point` can be used in `constexpr` computations, eg in `constexpr` functions. + +`constexpr` constructor has the same restrictions as a `constexpr` function and a class cannot have a virtual base class. ___ -

constexpr lambda

-

From C++17 all lambda functions are by default implicitly marked as constexpr, if possible. constexpr keyword can also be used explicitly.

+## `constexpr` lambda + +From C++17 all lambda functions are by default implicitly marked as `constexpr`, if possible. `constexpr` keyword can also be used explicitly. ```cpp auto squared = [](auto x) { // implicitly constexpr @@ -108,7 +117,7 @@ auto squared = [](auto x) constexpr { // OK ___ -

constexpr if

+## `constexpr if` ```cpp if constexpr (a < 0) @@ -119,12 +128,13 @@ else doSomethingElse(); ``` -

constexpr if selects only one block of instructions, depending on which condition is met. The condition and other blocks are not compiled in the binary. The condition must be a constant expression.

+`constexpr if` selects only one block of instructions, depending on which condition is met. The condition and other blocks are not compiled in the binary. The condition must be a constant expression. ___ -

constexpr if in SFINAE

-

constexpr if allows a simplification of template code used by SFINAE idiom.

+## `constexpr if` in SFINAE + +`constexpr if` allows a simplification of template code used by SFINAE idiom. ```cpp template; // C++17 diff --git a/module2/04-consteval-constinit.md b/module2/04-consteval-constinit.md new file mode 100644 index 0000000..a40597d --- /dev/null +++ b/module2/04-consteval-constinit.md @@ -0,0 +1,41 @@ + +# `consteval`, `constinit` + +___ + +## `consteval` keyword + +From C++20 we can use `consteval` for functions (only). + +`consteval` guarantees, that the function will be evaluated at the compile time. `constexpr` means that the function can also be executed at runtime. + +```cpp +consteval int sqr(int n) { + return n*n; +} +constexpr int r = sqr(100); // OK + +int x = 100; +int r2 = sqr(x); // Error: Call does not produce a constant +``` + + +___ + +## `constinit` keyword + +From C++20 we can use `constinit` for static or `thread_local` varaibles (tylko). + +`constinit` guarantees that the variable will have static initialization, that is either zero initialization or constant initialization. + +This eliminates the problem known as Static Initialization Order Fiasco. + +```cpp +const char *g() { return "dynamic initialization"; } +constexpr const char *f(bool p) { return p ? "constant initializer" : g(); } + +constinit const char *c = f(true); // OK +// constinit const char *d = f(false); // error + +``` + diff --git a/module2/05-noexcept.md b/module2/05-noexcept.md new file mode 100644 index 0000000..2ed6f07 --- /dev/null +++ b/module2/05-noexcept.md @@ -0,0 +1,82 @@ + +# `noexcept` + +___ + +## `noexcept` keyword + +**Rationale**: no-throw exception safety guarantee, less code generated for exceptions handling, additional compiler optimisation. + +Specifies whether a function will throw exceptions or not. If an exception is thrown out of a `noexcept` function, `std::terminate` is called. + + +```c++ +void foo() noexcept {} +void bar() noexcept { throw 42; } +// noexcept is the same as noexcept(true) + +int main() { + foo(); // fine + bar(); // compiles, but calls std::terminate +} +``` + + +___ + +## `noexcept` operator + +The `noexcept` operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. Returns bool. + +```cpp +void may_throw(); +void no_throw() noexcept; + +int main() { + std::cout << std::boolalpha + << "Is may_throw() noexcept? " + << noexcept(may_throw()) << '\n' // false + << "Is no_throw() noexcept? " + << noexcept(no_throw()) << '\n'; // true +} +``` + +___ + +## `noexcept` specifier + +Since C++17 exceptions specification is a part of the type system. Below functions are functions of two distinct types: + +* `void f() noexcept {}` +* `void f() {}` + +This change strengthens the type system, e.g. by allowing APIs to require non-throwing callbacks. + +___ + +## `throw` specifier + +`throw` specifier used after a function declaration was removed in C++17. It was marked as deprecated in C++11. + +```cpp +void f() throw(std::runtime_error); // f can throw std::runtime_error +void g() throw(std::runtime_error, std::logic_error); +``` + +Keeping the list of possible exceptions consistent with the implementation was usually impossible. + +___ + +## Remarks + +* Marking function as noexcept does not mean that you can't handle exceptions inside. +* noexcept means, that from this function no exception can be thrown (either directly by throw or indirectly when the exception is propagated). +* Inside noexcept functions you can freely use try-catch blocks to handle exceptions and not let them propagate outside. +* Using catch(...) is useless. +* Thanks to noexcept we can know what kind of exception occurred, because the binary will be terminated. We can handle this situation more properly rather than just ignoring the exception. + +___ + +## Exercise + +Mark `getArea()` and `getPerimeter()` methods in `Rectangle` as `noexcept`. diff --git a/module2/modern_cpp_dsa.md b/module2/06-dsa.md similarity index 69% rename from module2/modern_cpp_dsa.md rename to module2/06-dsa.md index 3a8d159..e3e355a 100644 --- a/module2/modern_cpp_dsa.md +++ b/module2/06-dsa.md @@ -1,9 +1,27 @@ -# Data structure alignment (`alignas`, `alignof`) +# Data structure alignment + +## `alignas`, `alignof` + +___ + +## `alignas` keyword + +```c++ +alignas(int) char variable; + +// every object of type see_t will be aligned to 16-byte boundary +struct alignas(16) see_t { + float see_data[4]; +}; + +// error: requested alignment is not a positive power of 2 +alignas(129) char cacheline[128]; +``` ___ -### _`alignas`_ keyword +## `alignas` keyword The `alignas` specifier may be applied to: @@ -11,36 +29,26 @@ The `alignas` specifier may be applied to: - the declaration or definition of a class/struct/union or enumeration `alignas(expression)` - expression needs to be positive power of 2. + `alignas(type-id)` - equivalent to `alignas(alignof(type-id))` + `alignas(0)` - has no effect + -**Exception:** if `alignas` would weaken the alignment the type have had without this `alignas`, it will not be applied. +If `alignas` would weaken the alignment the type have had without this `alignas`, it will not be applied. + ___ - -### _`alignas`_ keyword - -```c++ -// every object of type see_t will be alignet to 16-byte boundary -struct alignas(16) see_t { - float see_data[4]; -}; - -// error: requested alignment is not a positive power of 2 alignas(129) char cacheline[128]; -alignas(129) char cacheline[128]; -``` - -___ - -##### _`alignof`_ keyword + +## `alignof` keyword The `alignof` specifier returns a value of type `std::size_t`, which is alignment in bytes. If the type is reference type, the operator returns the alignment of referenced type; if the type is array type, alignment requirement of the element type is returned.
-
+
```c++ #include @@ -60,7 +68,7 @@ struct alignas(1) Double {
-
+
```c++ diff --git a/module2/modern_cpp_structure_bindings.md b/module2/07-structured-bindings.md similarity index 92% rename from module2/modern_cpp_structure_bindings.md rename to module2/07-structured-bindings.md index 30f5cca..a27e6bb 100644 --- a/module2/modern_cpp_structure_bindings.md +++ b/module2/07-structured-bindings.md @@ -1,6 +1,6 @@ # Structured bindings - + ___ ## Structured bindings @@ -41,7 +41,7 @@ std::unordered_map mapping { // De-structure by reference. for (const auto& [key, value] : mapping) { - // Do something with key and value + std::cout << key << " | " << value << '\n'; } ``` diff --git a/module2/modern_cpp_lambda.md b/module2/08-lambda.md similarity index 89% rename from module2/modern_cpp_lambda.md rename to module2/08-lambda.md index cc99a20..c60a0e3 100644 --- a/module2/modern_cpp_lambda.md +++ b/module2/08-lambda.md @@ -1,21 +1,7 @@ -# Lambda expressions in short +# Lambda expressions -___ - -## Lambda expressions - -**Rationale**: functional programming, in-place functions, more universal function passing - - -Lambda expression is defined directly in-place of its usage. Usually it is used as a parameter of another function that expects pointer to function or functor - in general a callable object. - - -Every lambda expression cause the compiler to create unique closure class that implements function operator with code from the expression. - - -Closure is an object of closure class. According to way of capture type this object keeps references or copies of local variables. - +## (in short) ___ @@ -31,6 +17,22 @@ auto result = l(2, 3); // result = 5 ___ +## Lambda expressions + +**Rationale**: functional programming, in-place functions, more universal function passing + + +Lambda expression is defined directly in-place of its usage. Usually it is used as a parameter of another function that expects a pointer to function or a functor - in general a callable object. + + +Every lambda expression cause the compiler to create unique closure class that implements function call operator with the code from the expression. + + +The closure is an object of a closure class. According to the way of capture type this object keeps references or copies of local variables. + + +___ + ## Lambda's returned type From C++14 automatic return type deduction from lambdas works quite good and usually there is no need to tell the returned type directly. However, it can be done using arrow operator. @@ -68,26 +70,6 @@ std::sort(values.begin(), values.end(), [](double a, double b) { Output: `0.4, -1.4, 4.0, 5.0, 7.9, -8.22` -___ - - -## Capture list - -Inside `[]` brackets we can include elements that the lambda should capture from the scope in which it is created. Also, the way how they are captured can be specified. - -* [] empty brackets means that inside the lambda no variable from outer scope can be used. -* [&] means that every variable from outer scope is captured by reference, including `this` pointer. - * Functor created by lambda expression can read and write to any captured variable and all of them are kept inside by lambda reference. -* [=] means that every variable from outer scope is capture by value, including `this` pointer. - * All used variables from the outer scope are copied to lambda expression and can be read only except for `this` pointer. - * `this` pointer when copied allows lambda to modify all variables it points to. - * You need a `mutable` keyword to modify values captured by `=`. -* [capture-list] allows to explicitly capture variable from the outer scope by mentioning their names on the list. - * By default all elements are captured by value. - * If variable should be captured by reference it should be precided by `&` whitch means capturing by reference. - * Example: `[a, &b]` -* [*this] (C++17) captures this pointer by value (creates a copy of this object). - ___ ## Capture list @@ -110,20 +92,46 @@ cout << "There are " << even_count << " even numbers in the vector." << endl; ``` +___ + + +## Capture list + +Inside `[]` brackets we can include elements that the lambda should capture from the scope in which it is created. Also, the way how they are captured can be specified. + +* [] empty brackets means that inside the lambda no variable from outer scope can be used. +* [&] means that every variable from outer scope is captured by reference, including `this` pointer. + * Functor created by lambda expression can read and write to any captured variable and all of them are kept inside by lambda reference. +* [=] means that every variable from outer scope is capture by value, including `this` pointer. + * All used variables from the outer scope are copied to lambda expression and can be read only except for `this` pointer. + * `this` pointer when copied allows lambda to modify all variables it points to. + * You need a `mutable` keyword to modify values captured by `=`. +* [capture-list] allows to explicitly capture variable from the outer scope by mentioning their names on the list. + * By default all elements are captured by value. + * If variable should be captured by reference it should be precided by `&` whitch means capturing by reference. + * Example: `[a, &b]` +* [*this] (C++17) captures this pointer by value (creates a copy of this object). + ___ ## Generic lambdas (C++14) In C++11 parameters of lambda expression must be declared with use of specific type. + C++14 allows to declare parameter as `auto`. - -This allows a compiler to deduce the type of lambda parameter in the same way parameters of the templates are deduced. In result compiler generates a code equivalent to closure class given below: + ```c++ auto lambda = [](auto x, auto y) { return x + y; } +``` + + +In result compiler generates a code equivalent to closure class given below: + +```c++ struct UnnamedClosureClass {// code generated by the compiler for above 1 line template auto operator()(T1 x, T2 y) const { diff --git a/module2/modern_cpp_other.md b/module2/09-other.md similarity index 71% rename from module2/modern_cpp_other.md rename to module2/09-other.md index c819200..ffec751 100644 --- a/module2/modern_cpp_other.md +++ b/module2/09-other.md @@ -3,9 +3,9 @@ ___ -## Nested namespace definitions (C++17) +## Nested namespace definitions -You can nest namespaces like this: +From C++17 you can nest namespaces like this: ```c++ namespace A::B::C { @@ -27,50 +27,64 @@ namespace A { ___ -## Class template argument deduction (C++17) +## Class template argument deduction From C++17 class template arguments can be deduced automatically. Automatic template argument deduction was available earlier only for template functions. ```c++ -std::pair p(1, 'x'); // C++17: OK, C++14: error: missing +std::pair p{1, 'x'}; // C++17: OK, C++14: error: missing //template arguments before p std::pair p(1, 'x'); // C++14: OK auto p = std::make_pair(1, 'x'); // C++17: OK, C++14: OK + +std::vector v = {1, 2, 3, 4}; // C++17: OK, std::vector ``` ___ -## Selection statements with initializer (C++17) +## Selection statements with initializer + +From C++17 there are new versions of the `if` and `switch` statements. -New versions of the `if` and `switch` statements for C++: +___ ### `if (init; condition)` ```cpp -status_code foo() { // C++14 - { //variable c scope - status_code c = bar(); - if (c != SUCCESS) { - return c; - } +status_code foo() { // C++17 + if (status_code c = bar(); c != SUCCESS) { + return c; } // ... } ``` + ```cpp -status_code foo() { // C++17 - if (status_code c = bar(); c != SUCCESS) { - return c; +status_code foo() { // C++14 + { //variable c scope + status_code c = bar(); + if (c != SUCCESS) { + return c; + } } // ... } ``` + ___ ## `switch (init; condition)` +```c++ +switch (Foo gadget(args); auto s = gadget.status()) { // C++17 + case OK: gadget.zip(); break; + case Bad: throw BadFoo(s.message()); +} +``` + + ```c++ { Foo gadget(args); @@ -80,16 +94,10 @@ ___ } } ``` - -```c++ -switch (Foo gadget(args); auto s = gadget.status()) { // C++17 - case OK: gadget.zip(); break; - case Bad: throw BadFoo(s.message()); -} -``` + ___ ## Overview -[Overview of modern C++ features](https://github.com/AnthonyCalandra/modern-cpp-features#stdfilesystem) +[Overview of modern C++ features](https://github.com/AnthonyCalandra/modern-cpp-features) diff --git a/module2/modern_cpp_recap.md b/module2/10-recap.md similarity index 100% rename from module2/modern_cpp_recap.md rename to module2/10-recap.md diff --git a/module2/pretest_answers.md b/module2/11-pretest-answers.md similarity index 68% rename from module2/pretest_answers.md rename to module2/11-pretest-answers.md index dd23d10..557da95 100644 --- a/module2/pretest_answers.md +++ b/module2/11-pretest-answers.md @@ -6,29 +6,14 @@ ___ -## Which lambda function is valid? +## Which lambda functions will compile? 1. []() -> int { return 4; }; 1. int [](){ return 4; }; 1. auto [](){ return 4; }; 1. []() -> auto {return 4; }; 1. [](){ return 4; }; -1. [] { return 4; } -1. [] mutable { return 4; } -1. [] -> int { return 4; } -1. int []{ return 4; } - -___ - -## Post-test - -Link to post-test will be sent to you in a next week :) - -___ - -## Feedback - -* What could be improved in this training? -* What was the most valuable for you? - -[Training evaluation](https://forms.gle/qEZFvYKdgbxkyxYj7) +1. [] { return 4; }; +1. [] mutable { return 4; }; +1. [] -> int { return 4; }; +1. int []{ return 4; }; diff --git a/module2/index.html b/module2/index.en.html similarity index 67% rename from module2/index.html rename to module2/index.en.html index ad06e28..d1c9d81 100644 --- a/module2/index.html +++ b/module2/index.en.html @@ -38,64 +38,53 @@

Kamil Szatkowski

# Agenda - * intro (15’) - * attributes (20’) - * constexpr (45’) - * β˜•οΈ break (15’) - * noexcept (25’) - * data structure alignment (alignas, alignof) (20’) - * structured bindings (30’) - * β˜•οΈ break (10’) - * lambda expressions in short (1h) - * 🍝 lunch break (50’) - * other useful features - review only (1h) - * recap (20’) + * attributes + * constexpr + * consteval, constinit + * noexcept + * data structure alignment (alignas, alignof) + * structured bindings + * lambda expressions in short + * other useful features - review only + * recap -
- -
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/module2/modern_cpp_noexcept.md b/module2/modern_cpp_noexcept.md deleted file mode 100644 index 52e075b..0000000 --- a/module2/modern_cpp_noexcept.md +++ /dev/null @@ -1,59 +0,0 @@ - -# `noexcept` - -___ - -## `noexcept` keyword - -**Rationale**: no-throw exception safety guarantee, less code generated for exceptions handling, additional compiler optimisation

- -Specifies whether a function will throw exceptions or not. If an exception is thrown out of a `noexcept` function, `std::terminate` is called. - - -```c++ -void bar() noexcept(true) {} -void baz() noexcept { throw 42; } -// noexcept is the same as noexcept(true) - -int main() { - bar(); // fine - baz(); // compiles, but calls std::terminate -} -``` - - -___ - -## `noexcept` operator - -The `noexcept` operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. Returns bool. - -```cpp -void may_throw(); -void no_throw() noexcept; - -int main() { - std::cout << std::boolalpha - << "Is may_throw() noexcept? " - << noexcept(may_throw()) << '\n' // false - << "Is no_throw() noexcept? " - << noexcept(no_throw()) << '\n'; // true -} -``` - -___ - -## `noexcept` keyword - -Since C++17 exceptions specification is a part of the type system. Below functions are functions of two distinct types: - -- `void f() noexcept(true);` -- `void f() noexcept(false);` - -This change strengthens the type system, e.g. by allowing APIs to require non-throwing callbacks. - -___ - -## Exercise - -Mark `getArea()` and `getPerimeter()` methods in `Rectangle` as `noexcept`. From 264c8733e46d782c1c557141726f0c7e999ad1fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Wed, 26 Jan 2022 13:23:31 +0100 Subject: [PATCH 3/9] modules renamed --- {module1 => 01-basic-features}/00-intro.md | 0 {module1 => 01-basic-features}/01-pretest.md | 0 {module1 => 01-basic-features}/02-standards.md | 0 {module1 => 01-basic-features}/03-static-assert.md | 0 {module1 => 01-basic-features}/04-nullptr.md | 0 {module1 => 01-basic-features}/05-scoped-enum.md | 0 {module1 => 01-basic-features}/06-auto.md | 0 {module1 => 01-basic-features}/07-using.md | 0 .../08-uniform-initialization.md | 0 .../09-default-delete-final-override.md | 0 {module1 => 01-basic-features}/10-recap.md | 0 .../11-pretest-answers.md | 0 {module1 => 01-basic-features}/12-decltype.md | 0 {module1 => 01-basic-features}/index.html | 0 .../modern_cpp_basic_features.pdf | Bin {module2 => 02-advanced-features}/00-intro.md | 0 {module2 => 02-advanced-features}/01-pretest.md | 0 {module2 => 02-advanced-features}/02-attributes.md | 0 {module2 => 02-advanced-features}/03-constexpr.md | 0 .../04-consteval-constinit.md | 0 {module2 => 02-advanced-features}/05-noexcept.md | 0 {module2 => 02-advanced-features}/06-dsa.md | 0 .../07-structured-bindings.md | 0 {module2 => 02-advanced-features}/08-lambda.md | 0 {module2 => 02-advanced-features}/09-other.md | 0 {module2 => 02-advanced-features}/10-recap.md | 0 .../11-pretest-answers.md | 0 {module2 => 02-advanced-features}/index.en.html | 0 .../modern_cpp_advanced_features.pdf | Bin {module3 => 03-move-semantics}/00-intro.md | 0 {module3 => 03-move-semantics}/01-pretest.md | 0 .../02-rvalues-lvalues.md | 0 {module3 => 03-move-semantics}/03-usage.md | 0 {module3 => 03-move-semantics}/04-implementation.md | 0 {module3 => 03-move-semantics}/05-rules.md | 0 {module3 => 03-move-semantics}/06-std-move.md | 0 .../07-reference-collapsing.md | 0 {module3 => 03-move-semantics}/08-std-forward.md | 0 {module3 => 03-move-semantics}/09-copy-elision.md | 0 .../10-knowledge-check.md | 0 .../11-pretest-answers.md | 0 {module3 => 03-move-semantics}/12-recap.md | 0 {module3 => 03-move-semantics}/bloat.cpp | 0 {module3 => 03-move-semantics}/index.html | 0 {module3 => 03-move-semantics}/move_semantics.pdf | Bin {module3 => 03-move-semantics}/rule0.cpp | 0 {module3 => 03-move-semantics}/rules.cpp | 0 {module3 => 03-move-semantics}/unique.cpp | 0 48 files changed, 0 insertions(+), 0 deletions(-) rename {module1 => 01-basic-features}/00-intro.md (100%) rename {module1 => 01-basic-features}/01-pretest.md (100%) rename {module1 => 01-basic-features}/02-standards.md (100%) rename {module1 => 01-basic-features}/03-static-assert.md (100%) rename {module1 => 01-basic-features}/04-nullptr.md (100%) rename {module1 => 01-basic-features}/05-scoped-enum.md (100%) rename {module1 => 01-basic-features}/06-auto.md (100%) rename {module1 => 01-basic-features}/07-using.md (100%) rename {module1 => 01-basic-features}/08-uniform-initialization.md (100%) rename {module1 => 01-basic-features}/09-default-delete-final-override.md (100%) rename {module1 => 01-basic-features}/10-recap.md (100%) rename {module1 => 01-basic-features}/11-pretest-answers.md (100%) rename {module1 => 01-basic-features}/12-decltype.md (100%) rename {module1 => 01-basic-features}/index.html (100%) rename {module1 => 01-basic-features}/modern_cpp_basic_features.pdf (100%) rename {module2 => 02-advanced-features}/00-intro.md (100%) rename {module2 => 02-advanced-features}/01-pretest.md (100%) rename {module2 => 02-advanced-features}/02-attributes.md (100%) rename {module2 => 02-advanced-features}/03-constexpr.md (100%) rename {module2 => 02-advanced-features}/04-consteval-constinit.md (100%) rename {module2 => 02-advanced-features}/05-noexcept.md (100%) rename {module2 => 02-advanced-features}/06-dsa.md (100%) rename {module2 => 02-advanced-features}/07-structured-bindings.md (100%) rename {module2 => 02-advanced-features}/08-lambda.md (100%) rename {module2 => 02-advanced-features}/09-other.md (100%) rename {module2 => 02-advanced-features}/10-recap.md (100%) rename {module2 => 02-advanced-features}/11-pretest-answers.md (100%) rename {module2 => 02-advanced-features}/index.en.html (100%) rename {module2 => 02-advanced-features}/modern_cpp_advanced_features.pdf (100%) rename {module3 => 03-move-semantics}/00-intro.md (100%) rename {module3 => 03-move-semantics}/01-pretest.md (100%) rename {module3 => 03-move-semantics}/02-rvalues-lvalues.md (100%) rename {module3 => 03-move-semantics}/03-usage.md (100%) rename {module3 => 03-move-semantics}/04-implementation.md (100%) rename {module3 => 03-move-semantics}/05-rules.md (100%) rename {module3 => 03-move-semantics}/06-std-move.md (100%) rename {module3 => 03-move-semantics}/07-reference-collapsing.md (100%) rename {module3 => 03-move-semantics}/08-std-forward.md (100%) rename {module3 => 03-move-semantics}/09-copy-elision.md (100%) rename {module3 => 03-move-semantics}/10-knowledge-check.md (100%) rename {module3 => 03-move-semantics}/11-pretest-answers.md (100%) rename {module3 => 03-move-semantics}/12-recap.md (100%) rename {module3 => 03-move-semantics}/bloat.cpp (100%) rename {module3 => 03-move-semantics}/index.html (100%) rename {module3 => 03-move-semantics}/move_semantics.pdf (100%) rename {module3 => 03-move-semantics}/rule0.cpp (100%) rename {module3 => 03-move-semantics}/rules.cpp (100%) rename {module3 => 03-move-semantics}/unique.cpp (100%) diff --git a/module1/00-intro.md b/01-basic-features/00-intro.md similarity index 100% rename from module1/00-intro.md rename to 01-basic-features/00-intro.md diff --git a/module1/01-pretest.md b/01-basic-features/01-pretest.md similarity index 100% rename from module1/01-pretest.md rename to 01-basic-features/01-pretest.md diff --git a/module1/02-standards.md b/01-basic-features/02-standards.md similarity index 100% rename from module1/02-standards.md rename to 01-basic-features/02-standards.md diff --git a/module1/03-static-assert.md b/01-basic-features/03-static-assert.md similarity index 100% rename from module1/03-static-assert.md rename to 01-basic-features/03-static-assert.md diff --git a/module1/04-nullptr.md b/01-basic-features/04-nullptr.md similarity index 100% rename from module1/04-nullptr.md rename to 01-basic-features/04-nullptr.md diff --git a/module1/05-scoped-enum.md b/01-basic-features/05-scoped-enum.md similarity index 100% rename from module1/05-scoped-enum.md rename to 01-basic-features/05-scoped-enum.md diff --git a/module1/06-auto.md b/01-basic-features/06-auto.md similarity index 100% rename from module1/06-auto.md rename to 01-basic-features/06-auto.md diff --git a/module1/07-using.md b/01-basic-features/07-using.md similarity index 100% rename from module1/07-using.md rename to 01-basic-features/07-using.md diff --git a/module1/08-uniform-initialization.md b/01-basic-features/08-uniform-initialization.md similarity index 100% rename from module1/08-uniform-initialization.md rename to 01-basic-features/08-uniform-initialization.md diff --git a/module1/09-default-delete-final-override.md b/01-basic-features/09-default-delete-final-override.md similarity index 100% rename from module1/09-default-delete-final-override.md rename to 01-basic-features/09-default-delete-final-override.md diff --git a/module1/10-recap.md b/01-basic-features/10-recap.md similarity index 100% rename from module1/10-recap.md rename to 01-basic-features/10-recap.md diff --git a/module1/11-pretest-answers.md b/01-basic-features/11-pretest-answers.md similarity index 100% rename from module1/11-pretest-answers.md rename to 01-basic-features/11-pretest-answers.md diff --git a/module1/12-decltype.md b/01-basic-features/12-decltype.md similarity index 100% rename from module1/12-decltype.md rename to 01-basic-features/12-decltype.md diff --git a/module1/index.html b/01-basic-features/index.html similarity index 100% rename from module1/index.html rename to 01-basic-features/index.html diff --git a/module1/modern_cpp_basic_features.pdf b/01-basic-features/modern_cpp_basic_features.pdf similarity index 100% rename from module1/modern_cpp_basic_features.pdf rename to 01-basic-features/modern_cpp_basic_features.pdf diff --git a/module2/00-intro.md b/02-advanced-features/00-intro.md similarity index 100% rename from module2/00-intro.md rename to 02-advanced-features/00-intro.md diff --git a/module2/01-pretest.md b/02-advanced-features/01-pretest.md similarity index 100% rename from module2/01-pretest.md rename to 02-advanced-features/01-pretest.md diff --git a/module2/02-attributes.md b/02-advanced-features/02-attributes.md similarity index 100% rename from module2/02-attributes.md rename to 02-advanced-features/02-attributes.md diff --git a/module2/03-constexpr.md b/02-advanced-features/03-constexpr.md similarity index 100% rename from module2/03-constexpr.md rename to 02-advanced-features/03-constexpr.md diff --git a/module2/04-consteval-constinit.md b/02-advanced-features/04-consteval-constinit.md similarity index 100% rename from module2/04-consteval-constinit.md rename to 02-advanced-features/04-consteval-constinit.md diff --git a/module2/05-noexcept.md b/02-advanced-features/05-noexcept.md similarity index 100% rename from module2/05-noexcept.md rename to 02-advanced-features/05-noexcept.md diff --git a/module2/06-dsa.md b/02-advanced-features/06-dsa.md similarity index 100% rename from module2/06-dsa.md rename to 02-advanced-features/06-dsa.md diff --git a/module2/07-structured-bindings.md b/02-advanced-features/07-structured-bindings.md similarity index 100% rename from module2/07-structured-bindings.md rename to 02-advanced-features/07-structured-bindings.md diff --git a/module2/08-lambda.md b/02-advanced-features/08-lambda.md similarity index 100% rename from module2/08-lambda.md rename to 02-advanced-features/08-lambda.md diff --git a/module2/09-other.md b/02-advanced-features/09-other.md similarity index 100% rename from module2/09-other.md rename to 02-advanced-features/09-other.md diff --git a/module2/10-recap.md b/02-advanced-features/10-recap.md similarity index 100% rename from module2/10-recap.md rename to 02-advanced-features/10-recap.md diff --git a/module2/11-pretest-answers.md b/02-advanced-features/11-pretest-answers.md similarity index 100% rename from module2/11-pretest-answers.md rename to 02-advanced-features/11-pretest-answers.md diff --git a/module2/index.en.html b/02-advanced-features/index.en.html similarity index 100% rename from module2/index.en.html rename to 02-advanced-features/index.en.html diff --git a/module2/modern_cpp_advanced_features.pdf b/02-advanced-features/modern_cpp_advanced_features.pdf similarity index 100% rename from module2/modern_cpp_advanced_features.pdf rename to 02-advanced-features/modern_cpp_advanced_features.pdf diff --git a/module3/00-intro.md b/03-move-semantics/00-intro.md similarity index 100% rename from module3/00-intro.md rename to 03-move-semantics/00-intro.md diff --git a/module3/01-pretest.md b/03-move-semantics/01-pretest.md similarity index 100% rename from module3/01-pretest.md rename to 03-move-semantics/01-pretest.md diff --git a/module3/02-rvalues-lvalues.md b/03-move-semantics/02-rvalues-lvalues.md similarity index 100% rename from module3/02-rvalues-lvalues.md rename to 03-move-semantics/02-rvalues-lvalues.md diff --git a/module3/03-usage.md b/03-move-semantics/03-usage.md similarity index 100% rename from module3/03-usage.md rename to 03-move-semantics/03-usage.md diff --git a/module3/04-implementation.md b/03-move-semantics/04-implementation.md similarity index 100% rename from module3/04-implementation.md rename to 03-move-semantics/04-implementation.md diff --git a/module3/05-rules.md b/03-move-semantics/05-rules.md similarity index 100% rename from module3/05-rules.md rename to 03-move-semantics/05-rules.md diff --git a/module3/06-std-move.md b/03-move-semantics/06-std-move.md similarity index 100% rename from module3/06-std-move.md rename to 03-move-semantics/06-std-move.md diff --git a/module3/07-reference-collapsing.md b/03-move-semantics/07-reference-collapsing.md similarity index 100% rename from module3/07-reference-collapsing.md rename to 03-move-semantics/07-reference-collapsing.md diff --git a/module3/08-std-forward.md b/03-move-semantics/08-std-forward.md similarity index 100% rename from module3/08-std-forward.md rename to 03-move-semantics/08-std-forward.md diff --git a/module3/09-copy-elision.md b/03-move-semantics/09-copy-elision.md similarity index 100% rename from module3/09-copy-elision.md rename to 03-move-semantics/09-copy-elision.md diff --git a/module3/10-knowledge-check.md b/03-move-semantics/10-knowledge-check.md similarity index 100% rename from module3/10-knowledge-check.md rename to 03-move-semantics/10-knowledge-check.md diff --git a/module3/11-pretest-answers.md b/03-move-semantics/11-pretest-answers.md similarity index 100% rename from module3/11-pretest-answers.md rename to 03-move-semantics/11-pretest-answers.md diff --git a/module3/12-recap.md b/03-move-semantics/12-recap.md similarity index 100% rename from module3/12-recap.md rename to 03-move-semantics/12-recap.md diff --git a/module3/bloat.cpp b/03-move-semantics/bloat.cpp similarity index 100% rename from module3/bloat.cpp rename to 03-move-semantics/bloat.cpp diff --git a/module3/index.html b/03-move-semantics/index.html similarity index 100% rename from module3/index.html rename to 03-move-semantics/index.html diff --git a/module3/move_semantics.pdf b/03-move-semantics/move_semantics.pdf similarity index 100% rename from module3/move_semantics.pdf rename to 03-move-semantics/move_semantics.pdf diff --git a/module3/rule0.cpp b/03-move-semantics/rule0.cpp similarity index 100% rename from module3/rule0.cpp rename to 03-move-semantics/rule0.cpp diff --git a/module3/rules.cpp b/03-move-semantics/rules.cpp similarity index 100% rename from module3/rules.cpp rename to 03-move-semantics/rules.cpp diff --git a/module3/unique.cpp b/03-move-semantics/unique.cpp similarity index 100% rename from module3/unique.cpp rename to 03-move-semantics/unique.cpp From 093ae21774cd8591674dae706ee71bba5ba57b44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Wed, 2 Feb 2022 11:39:13 +0100 Subject: [PATCH 4/9] presentation fixed --- 01-basic-features/08-uniform-initialization.md | 2 +- .../09-default-delete-final-override.md | 12 ++++++------ 01-basic-features/10-recap.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/01-basic-features/08-uniform-initialization.md b/01-basic-features/08-uniform-initialization.md index ea2230b..46a05a7 100644 --- a/01-basic-features/08-uniform-initialization.md +++ b/01-basic-features/08-uniform-initialization.md @@ -105,7 +105,7 @@ public: Bar<int> g(1, 2); // calls Bar(Type a, Type b) c-tor Bar<int> h = {}; // calls std::initializer_list c-tor // or default c-tor if exists -Bar<std::unique_ptr> c = {new int{1}, new int{2}}; +Bar<std::unique_ptr<int>> c = {new int{1}, new int{2}}; // error - std::unique_ptr is non-copyable diff --git a/01-basic-features/09-default-delete-final-override.md b/01-basic-features/09-default-delete-final-override.md index 44368af..7d60f2f 100644 --- a/01-basic-features/09-default-delete-final-override.md +++ b/01-basic-features/09-default-delete-final-override.md @@ -143,9 +143,9 @@ struct Base { ```cpp struct WithoutOverride : Base { void a(); // overrides Base::a() - void b(); // doesn't override B::b() const - virtual void c(); // overrides B::c() - void d(); // doesn't override B::d() + void b(); // doesn't override Base::b() const + virtual void c(); // overrides Base::c() + void d(); // doesn't override Base::d() }; ``` @@ -153,9 +153,9 @@ struct WithoutOverride : Base { ```cpp struct WithOverride : Base { void a() override; // OK - overrides Base::a() - void b() override; // error - doesn't override B::b() const - virtual void c() override; // OK - overrides B::c(char) - void d() override; // error - B::d() is not virtual + void b() override; // error - doesn't override Base::b() const + virtual void c() override; // OK - overrides Base::c() + void d() override; // error - Base::d() is not virtual }; ``` diff --git a/01-basic-features/10-recap.md b/01-basic-features/10-recap.md index 2e8a7ad..d72bc55 100644 --- a/01-basic-features/10-recap.md +++ b/01-basic-features/10-recap.md @@ -4,7 +4,7 @@ ___ -## What do you remember from today's session? +## What do you remember from Modern C++ session? 1. static_assert 2. nullptr From ff16eb1771f1e1a1bad30c8a47c872fcf5268975 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Wed, 2 Feb 2022 12:10:34 +0100 Subject: [PATCH 5/9] Update CMakeLists.txt --- shapes/CMakeLists.txt | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/shapes/CMakeLists.txt b/shapes/CMakeLists.txt index 149d118..f10c0b6 100644 --- a/shapes/CMakeLists.txt +++ b/shapes/CMakeLists.txt @@ -3,18 +3,6 @@ cmake_minimum_required(VERSION 3.11.0) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) -include(FetchContent) -FetchContent_Declare( - googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG main # release-1.10.0 -) -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -FetchContent_MakeAvailable(googletest) - -# Now simply link against gtest or gtest_main as needed. Eg - project(shapes) set(SRC_LIST @@ -26,10 +14,4 @@ set(SRC_LIST ) add_executable(${PROJECT_NAME} ${SRC_LIST}) -add_compile_options(${PROJECT_NAME} -Wall -Werror -Wpedantic -Wextra) - -include(GoogleTest) -gtest_discover_tests(${PROJECT_NAME}-ut) - -# shhh... don't ask about commented section ;) -# target_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Wpedantic -Wextra) +target_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Wpedantic -Wextra) From 1498d1c2029018eecc1c5a69ef1aaa0f9a7fb455 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Tue, 28 Jun 2022 17:01:53 +0200 Subject: [PATCH 6/9] Update 01-basic-features --- 01-basic-features/00-intro.md | 4 ++-- 01-basic-features/05-scoped-enum.md | 4 ++-- 01-basic-features/06-auto.md | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/01-basic-features/00-intro.md b/01-basic-features/00-intro.md index b21ce84..2eab32f 100644 --- a/01-basic-features/00-intro.md +++ b/01-basic-features/00-intro.md @@ -13,7 +13,7 @@ ___ ### Not only a programming XP * Frontend dev & DevOps @ Coders School -* C++ and Python developer @ Nokia & Credit Suisse +* C++ and Python developer @ Nokia, Credit Suisse, siili_auto * Team leader & Trainer @ Nokia * Scrum Master @ Nokia & Credit Suisse * Code Reviewer @ Nokia @@ -72,4 +72,4 @@ If you want to complain about the employer, I won't tell anyone ___ -### [Link to presentation on GitHub](https://github.com/coders-school/modern-cpp/tree/master/module1) +### [Link to the presentation](https://github.com/coders-school/modern-cpp/raw/main/01-basic-features/modern_cpp_basic_features.pdf) diff --git a/01-basic-features/05-scoped-enum.md b/01-basic-features/05-scoped-enum.md index f36d035..a46310a 100644 --- a/01-basic-features/05-scoped-enum.md +++ b/01-basic-features/05-scoped-enum.md @@ -82,11 +82,11 @@ ___ ## `enum` size -* Default enum size is sizeof(int) +* The default enum size is sizeof(int) * enum underlying type is extended automatically if values greater than int are provided * To save some memory we can define the underlying type using inheritance * A compiler will not allow defining value greater than the defined base can hold -* Inheritance work on both enum and enum class +* Inheritance works on both enum and enum class ___ diff --git a/01-basic-features/06-auto.md b/01-basic-features/06-auto.md index 40d9299..5aa9d00 100644 --- a/01-basic-features/06-auto.md +++ b/01-basic-features/06-auto.md @@ -149,7 +149,6 @@ ___ ``` ___ - ## Exercise From abab41b8b488571eaf3ccd1a511471d47156b46a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Tue, 28 Jun 2022 17:02:11 +0200 Subject: [PATCH 7/9] Update 02-advanced-features --- 02-advanced-features/00-intro.md | 13 ++++++++----- 02-advanced-features/03-constexpr.md | 2 +- 02-advanced-features/04-consteval-constinit.md | 2 +- 02-advanced-features/05-noexcept.md | 1 - 02-advanced-features/08-lambda.md | 1 + 02-advanced-features/10-recap.md | 2 +- 02-advanced-features/{index.en.html => index.html} | 0 7 files changed, 12 insertions(+), 9 deletions(-) rename 02-advanced-features/{index.en.html => index.html} (100%) diff --git a/02-advanced-features/00-intro.md b/02-advanced-features/00-intro.md index c54653d..18c5948 100644 --- a/02-advanced-features/00-intro.md +++ b/02-advanced-features/00-intro.md @@ -1,8 +1,7 @@ ## Let's get to know each other -* Your name and programming experience -* What you don't like in C++? -* Your hobbies +* What other programming languages do you use? +* Which C++ standard do you use/know? ___ @@ -12,8 +11,8 @@ ___ ### Not only a programming XP -* Entrepreneur & CEO @ Coders School -* C++ and Python developer @ Nokia & Credit Suisse +* Entrepreneur & Trainer @ Coders School +* C++ and Python developer @ Nokia, Credit Suisse, siili_auto * Team leader & Trainer @ Nokia * Scrum Master @ Nokia & Credit Suisse * Code Reviewer @ Nokia @@ -64,3 +63,7 @@ ___
  • β˜•οΈ Additional breaks on demand
  • ⌚️ Be on time
  • + +___ + +### [Link to the presentation](https://github.com/coders-school/modern-cpp/raw/main/02-advanced-features/modern_cpp_advanced_features.pdf) diff --git a/02-advanced-features/03-constexpr.md b/02-advanced-features/03-constexpr.md index 7dbe500..4b131b0 100644 --- a/02-advanced-features/03-constexpr.md +++ b/02-advanced-features/03-constexpr.md @@ -166,7 +166,7 @@ ___ Write a function that calculates n-th Fibonacci's number. Do not mark it `constexpr`. -In the first line of `main()` add computing 45-th Fibonacci's number. Measure the time of program execution (`time ./modern_cpp`) +In the first line of `main()` add computing 45-th Fibonacci's number. Measure the time of program execution (`time ./shapes`) Mark fibonacci function as `constexpr`, compile the program and measure the time of execution once again. diff --git a/02-advanced-features/04-consteval-constinit.md b/02-advanced-features/04-consteval-constinit.md index a40597d..ba055f1 100644 --- a/02-advanced-features/04-consteval-constinit.md +++ b/02-advanced-features/04-consteval-constinit.md @@ -24,7 +24,7 @@ ___ ## `constinit` keyword -From C++20 we can use `constinit` for static or `thread_local` varaibles (tylko). +From C++20 we can use `constinit` for static or `thread_local` varaibles (only). `constinit` guarantees that the variable will have static initialization, that is either zero initialization or constant initialization. diff --git a/02-advanced-features/05-noexcept.md b/02-advanced-features/05-noexcept.md index 2ed6f07..a1b5abc 100644 --- a/02-advanced-features/05-noexcept.md +++ b/02-advanced-features/05-noexcept.md @@ -72,7 +72,6 @@ ___ * Marking function as noexcept does not mean that you can't handle exceptions inside. * noexcept means, that from this function no exception can be thrown (either directly by throw or indirectly when the exception is propagated). * Inside noexcept functions you can freely use try-catch blocks to handle exceptions and not let them propagate outside. -* Using catch(...) is useless. * Thanks to noexcept we can know what kind of exception occurred, because the binary will be terminated. We can handle this situation more properly rather than just ignoring the exception. ___ diff --git a/02-advanced-features/08-lambda.md b/02-advanced-features/08-lambda.md index c60a0e3..c82e7ca 100644 --- a/02-advanced-features/08-lambda.md +++ b/02-advanced-features/08-lambda.md @@ -140,6 +140,7 @@ struct UnnamedClosureClass {// code generated by the compiler for above 1 line }; auto lambda = UnnamedClosureClass(); ``` + ___ diff --git a/02-advanced-features/10-recap.md b/02-advanced-features/10-recap.md index aacbf0a..779caee 100644 --- a/02-advanced-features/10-recap.md +++ b/02-advanced-features/10-recap.md @@ -11,4 +11,4 @@ ___ * Lambda - you need to add `mutable` in case you have `[=]` on capture list and you want to modify captured elements * Lambda - `unique_ptr` on capture list `a=std::move(a)` -* Try marking as many functions as `constexpr` as possible +* Try marking as many functions as `constexpr` and `noexcept` as possible diff --git a/02-advanced-features/index.en.html b/02-advanced-features/index.html similarity index 100% rename from 02-advanced-features/index.en.html rename to 02-advanced-features/index.html From 96cd3d2ec4309fa187e7d82b3cf1785a271295d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Tue, 13 Dec 2022 08:20:18 +0100 Subject: [PATCH 8/9] Update the repo information --- 01-basic-features/00-intro.md | 22 +++++++++++++++++++--- 01-basic-features/index.html | 2 +- 02-advanced-features/00-intro.md | 2 +- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/01-basic-features/00-intro.md b/01-basic-features/00-intro.md index 2eab32f..c2ce74a 100644 --- a/01-basic-features/00-intro.md +++ b/01-basic-features/00-intro.md @@ -1,8 +1,7 @@ ## Let's get to know each other * Your name and programming experience -* What you do not like in C++? -* Your hobbies +* What do you not like in C++? ___ @@ -72,4 +71,21 @@ If you want to complain about the employer, I won't tell anyone ___ -### [Link to the presentation](https://github.com/coders-school/modern-cpp/raw/main/01-basic-features/modern_cpp_basic_features.pdf) +### [Download the presentation](https://github.com/coders-school/modern-cpp/raw/english/01-basic-features/modern_cpp_basic_features.pdf) + +### Download the repo + +```sh +git clone https://github.com/coders-school/modern-cpp.git +cd modern-cpp +git checkout english +``` + +### Build the project + +```sh +cd shapes +mkdir build && cd build +cmake .. +make +``` diff --git a/01-basic-features/index.html b/01-basic-features/index.html index 26c50b4..54598bf 100644 --- a/01-basic-features/index.html +++ b/01-basic-features/index.html @@ -37,7 +37,7 @@

    Kamil Szatkowski

    ## Agenda - * intro (30’) + * intro (20’) * static_assert (15’) * nullptr (10’) * scoped enums (30’) diff --git a/02-advanced-features/00-intro.md b/02-advanced-features/00-intro.md index 18c5948..03a975f 100644 --- a/02-advanced-features/00-intro.md +++ b/02-advanced-features/00-intro.md @@ -66,4 +66,4 @@ ___ ___ -### [Link to the presentation](https://github.com/coders-school/modern-cpp/raw/main/02-advanced-features/modern_cpp_advanced_features.pdf) +### [Link to the presentation](https://github.com/coders-school/modern-cpp/raw/english/02-advanced-features/modern_cpp_advanced_features.pdf) From 9cbf620523a2ed2d64b7815280bbf75d9c4c094f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Ziobro=C5=84?= Date: Tue, 13 Dec 2022 14:56:56 +0100 Subject: [PATCH 9/9] Add today's work --- shapes/CMakeLists.txt | 2 +- shapes/Circle.cpp | 9 ++++--- shapes/Circle.hpp | 18 +++++++------- shapes/Rectangle.cpp | 9 ++----- shapes/Rectangle.hpp | 18 +++++++------- shapes/Shape.cpp | 20 ++++++++++++++++ shapes/Shape.hpp | 12 ++++++++++ shapes/Square.cpp | 13 ++++------ shapes/Square.hpp | 15 ++++++------ shapes/main.cpp | 55 ++++++++++++++++++++++++++++--------------- 10 files changed, 107 insertions(+), 64 deletions(-) diff --git a/shapes/CMakeLists.txt b/shapes/CMakeLists.txt index f10c0b6..1bc1ddb 100644 --- a/shapes/CMakeLists.txt +++ b/shapes/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.11.0) +cmake_minimum_required(VERSION 3.10.0) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/shapes/Circle.cpp b/shapes/Circle.cpp index bffbaed..8c7eb6c 100644 --- a/shapes/Circle.cpp +++ b/shapes/Circle.cpp @@ -6,13 +6,11 @@ Circle::Circle(double r) : r_(r) {} -Circle::Circle(const Circle & other) -{ - r_ = other.getRadius(); -} +static_assert(M_PI != 3.14, "M_PI is rounded"); double Circle::getArea() const { + // static_assert(1 > M_PI*100 % 314 > 0, "not enough precision for M_PI"); return M_PI * r_ * r_; } @@ -30,5 +28,6 @@ void Circle::print() const { std::cout << "Circle: radius: " << getRadius() << std::endl << " area: " << getArea() << std::endl - << " perimeter: " << getPerimeter() << std::endl; + << " perimeter: " << getPerimeter() << std::endl + << " color: " << getColor() << std::endl; } diff --git a/shapes/Circle.hpp b/shapes/Circle.hpp index 81897e7..b6abfff 100644 --- a/shapes/Circle.hpp +++ b/shapes/Circle.hpp @@ -1,20 +1,22 @@ #pragma once +#include #include "Shape.hpp" -class Circle : public Shape +class Circle final : public Shape { public: + Circle() = delete; // doesn't allow to call default constructor Circle(double r); - Circle(const Circle & other); + Circle(const Circle & other) = default; + using Shape::Shape; - double getArea() const; - double getPerimeter() const; + double getArea() const override; + double getPerimeter() const override; double getRadius() const; - void print() const; + void print() const override; private: - Circle(); // doesn't allow to call default constructor - - double r_; + static_assert(M_PI != 3.14, "M_PI is rounded"); + double r_ = 1.0; }; diff --git a/shapes/Rectangle.cpp b/shapes/Rectangle.cpp index 3e33a18..1b796b7 100644 --- a/shapes/Rectangle.cpp +++ b/shapes/Rectangle.cpp @@ -6,12 +6,6 @@ Rectangle::Rectangle(double x, double y) y_(y) {} -Rectangle::Rectangle(const Rectangle &other) -{ - x_ = other.getX(); - y_ = other.getY(); -} - double Rectangle::getArea() const { return x_ * y_; @@ -37,5 +31,6 @@ void Rectangle::print() const std::cout << "Rectangle: x: " << getX() << std::endl << " y: " << getY() << std::endl << " area: " << getArea() << std::endl - << " perimeter: " << getPerimeter() << std::endl; + << " perimeter: " << getPerimeter() << std::endl + << " color: " << getColor() << std::endl; } diff --git a/shapes/Rectangle.hpp b/shapes/Rectangle.hpp index 077aed1..ff458d5 100644 --- a/shapes/Rectangle.hpp +++ b/shapes/Rectangle.hpp @@ -5,18 +5,18 @@ class Rectangle : public Shape { public: + Rectangle() = delete; Rectangle(double x, double y); - Rectangle(const Rectangle & other); + Rectangle(const Rectangle & other) = default; + using Shape::Shape; - double getArea() const; - double getPerimeter() const; - double getX() const; + double getArea() const override; + double getPerimeter() const override; + virtual double getX() const final; double getY() const; - void print() const; + void print() const override; private: - Rectangle(); - - double x_; - double y_; + double x_ = 1.0; + double y_ = 1.0; }; diff --git a/shapes/Shape.cpp b/shapes/Shape.cpp index 65ccb25..5707c41 100644 --- a/shapes/Shape.cpp +++ b/shapes/Shape.cpp @@ -1,7 +1,27 @@ #include "Shape.hpp" #include +Shape::Shape(Color c) + : color(c) +{} + +Shape::Shape() +{} + void Shape::print() const { std::cout << "Unknown Shape" << std::endl; } + +std::string Shape::getColor() const +{ + switch (color) { + case Color::Red: + return "Red"; + case Color::Blue: + return "Blue"; + case Color::Green: + return "Green"; + } + return "Unknown"; +} \ No newline at end of file diff --git a/shapes/Shape.hpp b/shapes/Shape.hpp index d86bda6..a4550ff 100644 --- a/shapes/Shape.hpp +++ b/shapes/Shape.hpp @@ -1,11 +1,23 @@ #pragma once +#include + +enum struct Color : unsigned char { + Red, + Green, + Blue, +}; class Shape { + Color color = Color::Red; + public: + Shape(Color c); + Shape(); virtual ~Shape() {} virtual double getArea() const = 0; virtual double getPerimeter() const = 0; virtual void print() const; + std::string getColor() const; }; diff --git a/shapes/Square.cpp b/shapes/Square.cpp index 0ee9001..46790e3 100644 --- a/shapes/Square.cpp +++ b/shapes/Square.cpp @@ -5,23 +5,20 @@ Square::Square(double x) : Rectangle(x, x) {} -Square::Square(const Square &other) - : Rectangle(other.getX(), other.getX()) -{} - -double Square::getArea() +double Square::getArea() const { return getX() * getX(); } -double Square::getPerimeter() +double Square::getPerimeter() const { return 4 * getX(); } -void Square::print() +void Square::print() const { std::cout << "Square: x: " << getX() << std::endl << " area: " << getArea() << std::endl - << " perimeter: " << getPerimeter() << std::endl; + << " perimeter: " << getPerimeter() << std::endl + << " color: " << getColor() << std::endl; } diff --git a/shapes/Square.hpp b/shapes/Square.hpp index 676606b..cc2ff3b 100644 --- a/shapes/Square.hpp +++ b/shapes/Square.hpp @@ -5,14 +5,15 @@ class Square : public Rectangle { public: + Square() = delete; Square(double x); - Square(const Square & other); + Square(const Square & other) = default; + using Rectangle::Rectangle; - double getArea(); - double getPerimeter(); - void print(); + double getArea() const override; + double getPerimeter() const override; + void print() const override; + // double getX() const { return 1.0;} -private: - double getY(); // should not have Y dimension - Square(); + double getY() = delete; // should not have Y dimension }; diff --git a/shapes/main.cpp b/shapes/main.cpp index 87f2811..c36e681 100644 --- a/shapes/main.cpp +++ b/shapes/main.cpp @@ -10,16 +10,16 @@ using namespace std; -typedef vector> Collection; +using Collection = vector>; -bool sortByArea(shared_ptr first, shared_ptr second) +auto sortByArea(shared_ptr first, shared_ptr second) { if(first == nullptr || second == nullptr) return false; return (first->getArea() < second->getArea()); } -bool perimeterBiggerThan20(shared_ptr s) +auto perimeterBiggerThan20(shared_ptr s) { if(s) return (s->getPerimeter() > 20); @@ -35,23 +35,27 @@ bool areaLessThan10(shared_ptr s) void printCollectionElements(const Collection& collection) { - for(Collection::const_iterator it = collection.begin(); it != collection.end(); ++it) - if(*it) - (*it)->print(); + for (auto it : collection) { + if(it) { + it->print(); + } + } } void printAreas(const Collection& collection) { - for(vector>::const_iterator it = collection.begin(); it != collection.end(); ++it) - if(*it) - cout << (*it)->getArea() << std::endl; + for (auto it : collection) { + if (it) { + cout << it->getArea() << std::endl; + } + } } void findFirstShapeMatchingPredicate(const Collection& collection, bool (*predicate)(shared_ptr s), std::string info) { - Collection::const_iterator iter = std::find_if(collection.begin(), collection.end(), predicate); + auto iter = std::find_if(collection.begin(), collection.end(), predicate); if(*iter != nullptr) { cout << "First shape matching predicate: " << info << endl; @@ -65,14 +69,22 @@ void findFirstShapeMatchingPredicate(const Collection& collection, int main() { - Collection shapes; - shapes.push_back(make_shared(2.0)); - shapes.push_back(make_shared(3.0)); - shapes.push_back(nullptr); - shapes.push_back(make_shared(4.0)); - shapes.push_back(make_shared(10.0, 5.0)); - shapes.push_back(make_shared(3.0)); - shapes.push_back(make_shared(4.0)); + // std::vector v1{1, 2}; // 1, 2 + // std::vector v1 = {1, 2}; // 1, 2 + // std::vector v2(1, 2); // 2 + + Collection shapes = { + make_shared(2.0), + make_shared(3.0), + nullptr, + make_shared(4.0), + make_shared(10.0, 5.0), + make_shared(3.0), + make_shared(4.0), + make_shared(Color::Blue), + make_shared(Color::Green), + make_shared(Color::Red), + }; printCollectionElements(shapes); cout << "Areas before sort: " << std::endl; @@ -85,10 +97,15 @@ int main() auto square = make_shared(4.0); shapes.push_back(square); + // square->getY(); + // auto sq = make_shared(1.0); findFirstShapeMatchingPredicate(shapes, perimeterBiggerThan20, "perimeter bigger than 20"); findFirstShapeMatchingPredicate(shapes, areaLessThan10, "area less than 10"); + auto rect = make_shared(Color::Green); + auto rect2 = rect; + rect2->print(); + return 0; } -