Noutați

My Next Mentoring Program: “C++20: Get the Details”

Tweet Contents[Show] C++20: Get the Details: 16 Stations Mentoring Programs Competency Levels More Information?   Modern C++ Mentoring, My next mentoring program, “C++20: Get the Details”, starts in July. Registration will open in June.   Here is more information about my third mentoring program. C++20: Get the Details: The mentoring program consists of 16 stations. You have to invest at least 3 hours per week for each one. This means the program takes four months, and you can integrate my program into your workday. 16 Stations Introduction History C++ Compiler Standard Support Preparation Concepts Motivation Usage Placeholders Abbreviated Function Templates Concepts Predefined Concepts Definition of Concepts Requires Expressions User-Defined Concepts An Evolution or a Revolution Comparison Equality Comparison The Three-Way Comparison Operator Safe Comparison of Integers Constness consteval constinit std::is_constant_evaluated constexpr Containers and Algorithms Further Core Language Improvements Designated Initialization Templates Lambdas The Ranges Library Ranges and Views Characteristics Range Adaptors Comparison of std and std::ranges Algorithms Modules Advantages Module Interface Unit and Module Implementation Unit Submodules and Module Partitions Guidelines std::span and New Container Functions std::span Unified Deletion of Elements Uniform Checking of Elements String: starts_with and ends_with Formatting Library Overview Format String User-Defined Types Calendar and Time Zones Basic Types Time of Day Calendar Dates Time Zones Standard Library Utilities Mathematical Constants Midpoint and Linear Interpolation Bit Manipulation std::source_location Coroutines Characteristics The Framework Awaitables and Awaiters The Workflows Atomics std::atomic_flag std::atomic std::atomic_ref Synchronization and Coordination Latches and Barriers Semaphores Synchronized Output Streams Cooperative Interruption std::jthread  std::condition_variable_any std::stop_source, std::stop_token, and std::stop_callback C++20 is my third mentoring program. Here is more information about this program, “C++20: Get the Details” and more information about my mentoring programs: modernescpp.org. The following ones are open or will open in the next two years. Mentoring Programs October 2022: “Fundamentals for C++ Professionals” is open May 2023: “Design Patterns and Architectural Patterns with C++” is open July 2023: “C++20: Get the Details” will open (registration open in June) January 2023 – January 2025: The remaining mentoring programs are open for registration. I publish a new mentoring program each half a year. Here are the upcoming mentoring programs in the next two and a half years. Clean Code: Best Practices for Modern C++ Generic Programming (Templates) with C++ Concurrency with Modern C++ HPC with Modern C++   All mentoring programs are based on my books, classes, presentations, and posts. The mentoring programs have three different competency levels. Competency Levels   The competency levels of the mentoring programs are beginner, intermediate, and advanced. Beginner Fundamentals for C++ Professionals Intermediate Design Patterns and Architectural Patterns with C++ Clean Code: Best Practices for Modern C++ C++20: A Deep Insight Advanced Generic Programming (Templates) with C++ Concurrency with Modern C++ HPC with Modern C++ To master the intermediate or advanced mentoring programs, you must master the beginner mentoring program “Fundamentals for C++ Professionals” or any similar content. If you want to know more about the running mentoring programs “Fundamentals for C++ Professionals” or “Design Pattern and Architectural Pattern with C++“, follow the links. More Information? I host my mentoring program on modernescpp.org. I’m happy to answer your question:  This email address is being protected from spambots. You need JavaScript enabled to view it.. If you want to stay informed, subscribe here: https://bit.ly/ModernesCppMentorings     Modern C++ Mentoring,       […]

Read More

Dealing with Mutation: Locking

Tweet Contents[Show] Scoped Locking Strategized Locking Run-Time Polymorphism Compile-Time Polymorphism What’s Next? Locking is a classical way to protect a shared, mutable state. Today, I will present the two variants, Scoped Locking and Strategized Locking. Locking is a straightforward idea to protect a critical section. A critical section is a section of code that, at most, one thread can use at any time. Scoped Locking Scoped locking is the idea of RAII applied to a mutex. Scoped locking is also known as synchronized block and guard. The key idea of this idiom is to bind the resource acquisition and release to an object’s lifetime. As the name suggests, the lifetime of the object is scoped. Scoped means that the C++ run time is responsible for object destruction and, therefore, for releasing the resource. The class ScopedLock implements Scoped Locking. // scopedLock.cpp #include #include #include #include class ScopedLock{ private: std::mutex& mut; public: explicit ScopedLock(std::mutex& m): mut(m){ // (1) mut.lock(); // (2) std::cout

Read More

How To Change The Background Color Of A Memo In An FMX C++ App

C++ Builder is the easiest and fastest C++ IDE for building professional FMX C++ Apps with powerful GUI components like Memo, Edit, ListBox, StringGrid, and many more. Each component can be skinned with Styles to change their visual appearance. Styles are very powerful and because of this it can sometimes take a little to get used to how they work. In this post, we explain how to change the background color of a Memo (TMemo), one of the most frequently asked questions about using styles. These methods below can be applied to other components too. How to change the background color of a Memo in C++ Builder by using Styles? Styles are sets of graphical details that define the look and feel of an application. They are one of the most beautiful and useful UI features of RAD Studio that can really add some extra professionalism to your apps. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps (not wrapped in some kind of runtime interpretation layer) and the powerful FireMonkey (FMX) framework for cross-platform UIs. Both VCL and FMX C++ Apps support Styles. There are many styles in C++ Builder, and RAD Studio. More details about Styles can be found here. You can also find Premium Styles here. If you want to learn how you can modernize your components with styles this post has some great details; What are the steps to change the background color of a Memo in C++ Builder by using Styles? 1. Right-click on the Memo and select ‘Edit Custom Style…’ 2. Expand Memo1Style: you’ll see the background node. Click on background to select it. Then add a TRectangle via the Palette. The IDE should expand the background node and show a new Rectangle1Style tied to the TRectangle, 3. Via the Object Inspector change the Color of TRectangle as below 4. Click on the Apply Style button in the ‘Style Designer’, Save All. 5. Compile and run your application If you still have problems setting the color, this DocWiki article can help you: https://blogs.embarcadero.com/edit-custom-style-to-change-the-background-color-of-a-fmx-tedit/ How to change the background color of a Memo in C++ Builder code? If you want to change the background color of a Memo component (TMemo) in C++ Builder, first you should set the StyleLookup to “Memostyle” as shown below: Memo1->StyleLookup = “Memostyle”; If you look at the Custom Style of Memo, There is a “background” property, so we should find this resource by using FindStyleResource() method of Memo as given in the example below: Memo1->StyleLookup = “Memostyle”; auto fmxobj = Edit1->FindStyleResource(“background”, false); If this resource object we can create a rectangle (TRectangle) as a background: std::unique_ptr<TRectangle> rect(new TRectangle(fmxobj)); Here we used unique_ptr which more modern to create this rectangle. Now we can set properties of our Rectangle, including its color. rect->Align = TAlignLayout::Client; rect->Fill->Color = color; rect->Stroke->Color = color; // = claNull; rect->HitTest = false; rect->SendToBack(); Now, at last we need to add this object by using the .get() method of unique_ptr. And the final trick here is you must release this unique_ptr by using .release() otherwise it doesn’t have any effect. fmxobj->AddObject(rect.get()); rect.release(); Is there a full example of how to change the background color of a Memo in C++ Builder code? Here is a full C++ Builder FMX FMX C++ Apps example that changes the color of 3 TMemo components that has Memo1, Memo2, Memo3 names. To do this we create a ChangeMemoColor() function that uses the […]

Read More

How To Use A Game Pad Or Joystick Controller In C++ On Windows

C++ On Windows is one of the most powerful programming languages that we use for all sorts of purposes, from regular applications, games, business, industrial infrastructure, robotics, and in the control of IoT devices. The most well-known controllers for those areas where human and computer interaction are important and stretches beyond simple keyboard input are joysticks or gamepads. One of the simplest examples to use them on Windows is using the venerable XInput library which has been around for quite a long time but can still be easily used with the latest C++ Compiler. In this post, we explain how you can use a gamepad or joystick controller in C++ On Windows with Xinput library. Is there a component for the gamepad or joystick in C++ On Windows? If you are looking for a ready-to-use component library, there are Delphi and C++ Builder-compatible components built on the XInput library. For example, the Controller library is a Delphi and C++ Builder component that allows applications to receive input from an Xbox Controller. The main features of this library are, Uses Windows XInput API. Available for Delphi/C++ Builder 6 – 11 and Lazarus 2.0.12. Source code included in the registered version. Royalty free distribution. You can download the trial version of the XInput library or you can buy a professional edition from Winsoft.sk. How can I control a gamepad or joystick in C++ with the Xinput Library? The XInput library is deprecated but it still supported by Microsoft. They recommend moving towards the GameInput library or Windows.Game.Input for Windows applications. If we look at these kinds of libraries (i.e GamePad.h library), like MS’ own DirectXTK, we can see that the toolkit allows one to define USING_XINPUT vs. USING_GAMEINPUT vs. USING_WINDOWS_GAMING_INPUT to pick which underlying library is used. If we compare  XInput compared to GameInput: XInput library is fairly old and easy to implement Windows applications. XInput library is limited to 4 controllers. XInput library has no uniform interface to other inputs (like mouse/keyboard). XInput library input occurs with higher latency. XInput library is not friendly with other controllers. i.e. no support for Xbox One Rumble Motors. So, briefly, DirectInput is a better long-term choice than XInput. If you still want to use XInput, you can read more about https://learn.microsoft.com/en-us/windows/win32/xinput/getting-started-with-xinput XINPUT_GAMEPAD structure (declared in ) is explained here : https://learn.microsoft.com/en-us/windows/win32/api/xinput/ns-xinput-xinput_gamepad As in there, this structure has these members: wButtons, bLeftTrigger, bRightTrigger, sThumbLX, sThumbLY, sThumbRX, sThumbRY. Here wButtons member is used as a bitmask of the device digital buttons, it can be used as below, wButtons Device digital button flags Gamepad Bitmask XINPUT_GAMEPAD_DPAD_UP 0x0001 XINPUT_GAMEPAD_DPAD_DOWN 0x0002 XINPUT_GAMEPAD_DPAD_LEFT 0x0004 XINPUT_GAMEPAD_DPAD_RIGHT 0x0008 XINPUT_GAMEPAD_START 0x0010 XINPUT_GAMEPAD_BACK 0x0020 XINPUT_GAMEPAD_LEFT_THUMB 0x0040 XINPUT_GAMEPAD_RIGHT_THUMB 0x0080 XINPUT_GAMEPAD_LEFT_SHOULDER 0x0100 XINPUT_GAMEPAD_RIGHT_SHOULDER 0x0200 XINPUT_GAMEPAD_A 0x1000 XINPUT_GAMEPAD_B 0x2000 XINPUT_GAMEPAD_X 0x4000 XINPUT_GAMEPAD_Y 0x8000 How to use a gamepad or joystick in C++? If you wonder how XInput library works, you can create a simple example as in given steps below. First, we need library header to use XInput library. This is how you can use XInput library in C++. #include #include #include #pragma comment(lib, “XInput.lib”) Now, lets create a TController class that have n for the controller number and state for it. Here is an example. class TController { private: int n; XINPUT_STATE state; public:             // add controller methods here }; Then we need to add some methods for this class, first lets set our private controller number n in construction like […]

Read More

Advantages and Disadvantages of The C++ Programming Language

In the last 40 years C++ has earned, and maintained, a reputation as one of the most efficient programming languages. C++ is still hugely popular, often in the top 3 of any lists of popular programming languages and is used widely across a wide array of operating systems. Choosing the right programming language and IDE (we call them C++ tools) are very important in the early stages of learning to program. Generally, new developers want to know the advantages and disadvantages of the C++ programming language, and in this post, we try to explain its pros and cons for you. What are the pros and cons of C++ programming language? What are the advantages of C++? 1. C++ is compiler-based with very fast execution times C++ is a compiler-based programming language and that helps make it the fastest and one of the most powerful programming languages. This is one of the reasons to use hardware and software algorithms efficiently. In general, there are two types of programming languages: Interpreted and Non-Interpreted (Compiled). All computers work with something called machine code (code that can be directly executed by the computer’s CPU) that tells the computer what to do. This is the most native and fastest code, but it requires writing many lines for even quite simple things and is hard to generalize for all kinds of machines. It’s also not very easy to understand for humans. A compiler (C or C++ Compiler, etc.) is a computer program that converts a program written in a ‘high level’ programming language such as C++ code into executable machine code. The high-level language looks more like English and is much easier to understand and less complicated. 2. C++ is a structured and object oriented programming language C++ allows developers to use C language which is a structured programming language and it also allows Object Oriented Programming. Object Oriented Programming (OOP) is a way to integrate with objects which can contain data in the form of attributes or properties of objects, and code blocks in the form of methods, and functions of objects. These attributes and methods that belong to the class are generally referred to as class members. Object-Oriented Programming is a good way to work on data and work with functions in memory. Classes and Objects are the best way to work on properties and functions. Object-Oriented Programming has many advantages over procedural programming and it is the most characteristic feature of the visual and modern C++ programming language. 3. C++ supports visual 2D, 3D and GUI-based programming C++ is useful to make GUI-based applications on Windows, iOS, Android, Mac OS, Linux, and many other less popular OSes. C++ has different GUI frameworks i.e. VCL, FMX, GTK, and other Visual components. Modern C++ has been enhanced with Visual Bindings, High-DPI 4K supports, responsive features, skinned UI elements, glamorous one-click GUI sets, 2D and 3D components like OpenGL, Skia, and Viewport3D; and has many game engines like Unreal Engine, Unity, O3DE. C++ is also useful to develop graphical 2D and 3D applications, real-time computational simulations, and analysis, C++ highly uses CPU and GPU-based applications with graphical supports like Physics, OpenCL, Vulkan, HPC, etc. 4. C++ is a mid-level programming language with low-level capabilities Because of its capability in assembly-level coding and compiling abilities, I prefer calling C a ‘close to low-level language’. Briefly, we may say C and C++ languages are close […]

Read More

How To Use Base-8 (Octal) Numbers In Modern C++?

In general, in nearly all programming languages, including Modern C++, we use base-10 numbers, while our computer hardware uses the binary base-2 system (bits). I personally believe that base-10 is because we typically have 10 fingers and since we learn to counting on our fingers we use base-10 primarily. However, due to the way binary works it is sometimes convenient to use base-8 system octal (oct) and base-16 system hexadecimal (hex) numbers in programming. In this post, we explain how to use Base-8 octal numbers in Modern C++. What is the octal number system? The octal – or oct – number system is the base-8 system, Octal uses the digits from 0 to 7. In general, we use a base-10 number system in normal life. In the digital world we also use base-2, base-8, and base-16 as well as base-10. If you want to explore the different numbering systems, try this Wikipedia article. Let’s give some octal examples and their values in the decimal system, 1octal  = 1 10octal  = 8 100octal = 64 How to declare base-8 (octal) number in modern C++? In C++, when we use octal numbers in C++ code, we put 0 on the left side of an octal number. This zero shows it is an octal representation. int x; // 015 in octal is 13 base10 or decimal x = 015; How to initialize base-8 (octal) number in modern C++? here the first zero on the left side of 0010 defines this number representation is an octal representation. The integer x value is results as 8; How to set an integer to base-8 (octal) number in modern C++? We can use std::istringstream() which is declared in library. Here Octal number “010” is declared into x as a octal number, now when you print this variable, it will be displayed in octal decimal system,    int x;    std::istringstream(“010”) >> std::oct >> x;    std::cout << x << std::endl; How to print out base-8 (octal) number in modern C++? When we print out base-8 (octal) numbers we use std::oct format as below, int x = 0010; std::cout << std::oct << x << std::endl; How to print out base-8 (octal) number in C language? C has very powerful printf() function and there is a ‘%o‘ Format Specifier to print out octal numbers. How to display base-8 (octal) number in C++ Builder? C++ Builder is using UnicodeString in most of components, and UnicodeString very powerful printf() method. There is a ‘%o‘ Format Specifier to print out octal numbers that can be used as below, int i = 64; // decimal UnicodeString ustr; ustr.printf(“%o n”, i); Edit1->Text = ustr; How to convert base-8 (octal) number to (base-10) decimal number in modern C++? When you declare an integer with octal representation, it is automatically converted to base-10 number. For example: here a = 8 in the decimal system. there is another method std::stoi that converts octal representation in string to an integer. Here is an example, int x = std::stoi(“011”, 0, 8); std::cout << x << std::endl; How to convert (base-10) decimal number to base-8 (octal) number in modern C++? In C++, computation is done in base-2 while you have a decimal number. If you want to convert base-10 decimal number to base-8 octal number, you only need to convert to a octal number or string when you […]

Read More

Dealing with Sharing C++

If you don’t use Sharing C++, no data races can happen. Not sharing means that your thread works on local variables. This can be achieved by copying the value, using thread-specific storage, or transferring the result of a thread to its associated future via a protected data channel. The patterns in this section are quite obvious, but I will present them with a short explanation for completeness. Let me start with Copied Value. Copied Value Sharing C++ If a thread gets its arguments by copy and not by reference, there is no need to synchronize access to any data. No data races and no lifetime issues are possible. Data Races with References The following program creates three threads. One thread gets its argument by copy, the other by reference, and the last by constant reference. // copiedValueDataRace.cpp #include #include #include #include using namespace std::chrono_literals; void byCopy(bool b){ std::this_thread::sleep_for(1ms); // (1) std::cout << “byCopy: ” << b << ‘n’; } void byReference(bool& b){ std::this_thread::sleep_for(1ms); // (2) std::cout << “byReference: ” << b << ‘n’; } void byConstReference(const bool& b){ std::this_thread::sleep_for(1ms); // (3) std::cout << “byConstReference: ” << b << ‘n’; } int main(){ std::cout << std::boolalpha << ‘n’; bool shared{false}; std::thread t1(byCopy, shared); std::thread t2(byReference, std::ref(shared)); std::thread t3(byConstReference, std::cref(shared)); shared = true; t1.join(); t2.join(); t3.join(); std::cout << ‘n’; } Each thread sleeps for one millisecond (lines 1, 2, and 3) before displaying the boolean value. Only the thread t1 has a local copy of the boolean and has, therefore, no data race. The program’s output shows that the boolean values of threads t2 and t3 are modified without synchronization. You may think that the thread t3 in the previous example copiedValueDataRace.cpp can just be replaced with std::thread t3(byConstReference, shared). The program compiles and runs, but what seems like a reference is a copy. The reason is that the type traits function std::decay is applied to each thread argument. std::decay performs lvalue-to-rvalue, array-to-pointer, and function-to-pointer implicit conversions to its type T. In particular, it invokes, in this case, the type traits function std::remove_reference on the type T. The following program perConstReference.cpp uses a non-copyable type NonCopyableClass. // perConstReference.cpp #include class NonCopyableClass{ public: // the compiler generated default constructor NonCopyableClass() = default; // disallow copying NonCopyableClass& operator = (const NonCopyableClass&) = delete; NonCopyableClass (const NonCopyableClass&) = delete; }; void perConstReference(const NonCopyableClass& nonCopy){} int main(){ NonCopyableClass nonCopy; // (1) perConstReference(nonCopy); // (2) std::thread t(perConstReference, nonCopy); // (3) t.join(); } The object nonCopy (line 1) is not copyable. This is fine if I invoke the function perConstReference with the argument nonCopy (line 2) because the function accepts its argument per constant reference. Using the same function in the thread t (line 3) causes GCC to generate a verbose compiler error with more than 300 lines: The error message’s essential part is in the middle of the screenshot in red rounded rectangle: “error: use of deleted function”. The copy-constructor of the class NonCopyableClass is not available. When you borrow something, you have to ensure that the underlying value is still available when you use it. Lifetime Issues with References If a thread uses its argument by reference and you detach the thread, you have to be extremely careful. The small program copiedValueLifetimeIssues.cpp has undefined behavior. // copiedValueLifetimeIssues.cpp #include #include #include void executeTwoThreads(){ // (1) const std::string […]

Read More

What Are Declared True Constants In Modern C++?

C++ has many different variable types to develop modern applications with modern C++ IDE‘s and compilers. Several different language constructs are referred to as ‘constants’. There are numeric constants and string constants. Every enumerated type defines constants that represent the values of that type. Declared constants are either true constants or typed constants. In this post, we will explain what we mean by a declared constant and what is a true constant which is a kind of declared constant in C++. What are declared constants in Modern C++? Several different language constructions are referred to as ‘constants’. There are numeric constants (also called numerals) like 17, and string constants (also called character strings or string literals) like ‘Hello world!’. Every enumerated type defines constants that represent the values of that type. There are predefined constants like True, False, and nil. Finally, there are constants that, like variables, are created individually by declaration. Declared constants are either true constants or typed constants. There are predefined constants like True, False, and nil. Finally, there are constants that, like variables, are created individually by declaration. These two kinds of constant are superficially similar, but they are governed by different rules and used for different purposes. What are true constants in Modern C++? A true constant is a declared identifier whose value cannot change. The syntax for declaring a true constant is: const identifier = constantExpression; For example: declares a constant called MaxValue that returns the integer 237. Where identifier is any valid identifier and constantExpression is an expression that the compiler can evaluate without executing your program. If constantExpression returns an ordinal value, you can specify the type of the declared constant using a value typecast. For example: const MyNumber = Int64(17); declares a constant called MyNumber, of type Int64, that returns the integer 17. Otherwise, the type of the declared constant is the type of the constantExpression. If constantExpression is a character string, the declared constant is compatible with any string type. If the character string is of length 1, it is also compatible with any character type. If constantExpression is a real, its type is Extended. If it is an integer, its type is given by the table below. Types for integer constants Range of constant (hexadecimal) Range of constant (decimal) Type Aliases 0 $FF 0 255 Byte UInt8 0 $FFFF 0 65535 Word UInt16 0 $FFFFFFFF 0 4294967295 Cardinal UInt32, FixedUInt 0 $FFFFFFFFFFFFFFFF 0 18446744073709551615 UInt64 -$80 $7F -128 127 ShortInt Int8 -$8000 $7FFF -32768 32767 SmallInt Int16 -$80000000 $7FFFFFFF -2147483648 2147483647 Integer Int32, FixedInt -$8000000000000000 $7FFFFFFFFFFFFFFF -9223372036854775808 9223372036854775807 Int64 32-bit native integer type Range of constant (hexadecimal) Range of constant (decimal) Type Equivalent type -$80000000 $7FFFFFFF -2147483648 2147483647 NativeInt Integer 0 $FFFFFFFF 0 4294967295 NativeUInt Cardinal 64-bit native integer type Range of constant (hexadecimal) Range of constant (decimal) Type Equivalent type -$8000000000000000 $7FFFFFFFFFFFFFFF -9223372036854775808 9223372036854775807 NativeInt Int64 0 $FFFFFFFFFFFFFFFF 0 18446744073709551615 NativeUInt UInt64 32-bit platforms and 64-bit Windows integer type 32-bit platforms include 32-bit Windows and Android. Range of constant (hexadecimal) Range of constant (decimal) Type Equivalent type -$80000000 $7FFFFFFF -2147483648 2147483647 LongInt Integer 0 $FFFFFFFF 0 4294967295 LongWord Cardinal 64-bit platforms integer type excluding 64-bit Windows 64-bit platforms include 64-bit iOS, 64-bit Android, 64-bit macOS and 64-bit Linux. Range of constant (hexadecimal) Range of constant (decimal) Type Equivalent type -$8000000000000000 $7FFFFFFFFFFFFFFF -9223372036854775808 9223372036854775807 LongInt Int64 0 $FFFFFFFFFFFFFFFF 0 18446744073709551615 LongWord UInt64 Here are some examples of constant declarations: 1 2 3 4 5 6 7 8 […]

Read More

5 Easy Things To Learn Using C++ Builder 11 CE

Hello C++ developers, C++ students, and C++ educators. This week was another milestone for the C++ programming language with a free version of C++ Builder, C++ Builder 11 CE Community Edition released on April 2023. If you are a start-up developer, student, hobbyist or just interested in learning to code then C++ Builder Community Edition may well be just the thing for you. Read the FAQ notes on the CE license and then simply fill out the form and download C++ Builder 11 CE. Table of Contents Where can I learn to program in C++ for free? What is new in C++ Builder CE? What are the important features of C++ that can be used with C++ Builder CE? Did you know you can create iOS programs for free with the C++ Builder Community Edition? Learn C++ Builder CE with C++ examples Get in touch and tell us what you’d like to see on the blogs What might be next for C++ Builder? Where can I learn to program in C++ for free? If you don’t know anything about C++ or the C++ Builder IDE, don’t worry, we have a lot of examples on LearnCPlusPlus.org website and they’re all completely free. Just visit this site and copy and paste any examples there into a new Console, VCL, or FMX project, depending on the post example. We keep adding more C and C++ posts with sample code. In today’s round-up of recent posts on LearnCPlusPlus.org, we have new C and C++ posts with very simple examples that can be used with, The free version of C++ Builder 11 CE Community Edition or a professional C++ Builder or free BCC32C C++ Compiler and BCC32X C++ Compiler or the free Dev-C++ What is new in C++ Builder CE? C++ Builder 11 CE which is the free Edition of C++ Builder has been recently released. Embarcadero has made available a Community Edition license for the most recent 11.3 release of Delphi and C++Builder. This is a free edition of either Delphi or C++Builder for students, hobbyists, and startups (as the license is revenue-limited). What are the important features of C++ that can be used with C++ Builder CE? C++ is a well-established programming language that is supported by a big community for many different computing hardware platforms. The language has a set of standards generally named after the approximate year the standard was adopted, such as C++98, C++11, C++14, C++17, and so on. Basically, these standards are an international agreement for C++ compiler technology. If you are using a feature from one of the standards, for example a lambda, and you have some problems, referring to the standard may be helpful in understanding the high-level technical details. In the first post, we explain what the C++ standards are, and where to find them. https://learncplusplus.org/where-to-find-the-c-standards-in-2023/ In C++, there are function macros for the fixed-width integer type that expands to an integer constant expression having the value specified by its argument. Their type is the promoted type of std::int_least8_t, std::int_least16_t, std::int_least32_t, and std::int_least64_t and unsigned versions of these types respectively. In the next post, we explain these function macros for integer constants in Modern C++. https://learncplusplus.org/what-are-function-macros-for-integer-constants/ In another post, we describe the macros for fixed-width integer types in C++ that allow you to obtain minimum and maximum possible values. In that post, we explain these macros for integer […]

Read More

Reactor

Reactor Also known as Problem  Solution Structure Dynamic Behavior Example Pros and Cons Pros Cons What’s Next? Event-driven applications, such as GUIs or servers, often apply the architecture pattern Reactor. A Reactor can accept multiple requests simultaneously and distribute them to different handlers. The Reactor Pattern is an event-driven framework to concurrently demultiplex and dispatch service requests to various service providers. The requests are processed synchronously. Reactor Also known as Dispatcher Notifier Problem A server should answer several client requests simultaneously be performant, stable, and scalable be extendable to support new or improved services The application should be hidden from multi-threading and synchronization challenges  Solution Each supported service is encapsulated in a handler The handlers are registered within the Reactor The Reactor uses an event demultiplexer to wait synchronously on all incoming events When the Reactor is notified, it dispatches the service request to the specific handler Structure Handles The handles identify different event sources, such as network connections, open files, or GUI events. The event source generates events such as connect, read, or write queued on the associated handle. Synchronous event demultiplexer The synchronous event demultiplexer waits for one or more indication events and blocks until the associated handle can process the event. The system calls select, poll, epoll, kqueue, or WaitForMultipleObjects enable it to wait for indication events. Event handler The event handler defines the interface for processing the indication events. The event handler defines the supported services of the application. Concrete event handler The concrete event handler implements the interface of the application defined by the event handler. Reactor The Reactor supports an interface to register and deregister the concrete event handler using file descriptors. The Reactor uses a synchronous event demultiplexer to wait for indication events. An indication event can be a reading event, a writing event, or an error event. The Reactor maps the events to their concrete event handler. The Reactor manages the lifetime of the event loop. The Reactor (not the application) waits for the indication events to demultiplex and dispatch the event. The concrete event handlers are registered within the Reactor. The Reactor inverts the flow of control. This inversion of control is often called Hollywood principle. The dynamic behavior of a Reactor is pretty interesting. Dynamic Behavior The following points illustrate the control flow between the Reactor and the event handler. The application registers an event handler for specific events in the Reactor. Each event handler provides its specific handler to the Reactor. The application starts the event loop. The event loop waits for indication events. The event demultiplexer returns to the Reactor when an event source becomes ready. The Reactor dispatches the handles to the corresponding event handler. The event handler processes the event. Let’s study the Reactor in action. This example uses the POCO framework. “The POCO C++ Libraries are powerful cross-platform C++ libraries for building network- and internet-based applications that run on desktop, server, mobile, IoT, and embedded systems.” // reactor.cpp #include #include #include “Poco/Net/SocketReactor.h” #include “Poco/Net/SocketAcceptor.h” #include “Poco/Net/SocketNotification.h” #include “Poco/Net/StreamSocket.h” #include “Poco/Net/ServerSocket.h” #include “Poco/Observer.h” #include “Poco/Thread.h” #include “Poco/Util/ServerApplication.h” using Poco::Observer; using Poco::Thread; using Poco::Net::ReadableNotification; using Poco::Net::ServerSocket; using Poco::Net::ShutdownNotification; using Poco::Net::SocketAcceptor; using Poco::Net::SocketReactor; using Poco::Net::StreamSocket; using Poco::Util::Application; class EchoHandler { public: EchoHandler(const StreamSocket& s, SocketReactor& r): socket(s), reactor(r) { // (11) reactor.addEventHandler(socket, Observer<EchoHandler, ReadableNotification>(*this, &EchoHandler::socketReadable)); } void socketReadable(ReadableNotification*) […]

Read More