C++ Builder

Learn How to Use New And Delete Elisions In C++

The C++14 standard (and later), brings a lot of useful smart pointers and improvements on them. They help us to avoid the mistake of incorrectly freeing the memory addressed by pointers. In modern C++, we have the new and delete operators that are used to allocate and free objects from memory, and in this post, we explain how to use new and delete operators. Can we use new and delete elisions in modern C++ or is it obsolete? Allocating memory and freeing it safely is hard if you are programming a very big application. In Modern C++, there are smart pointers that help avoid the mistake of incorrectly freeing the memory addressed by pointers. Smart pointers make it easy to define pointers, they came with C++11. The most used types of C++ smart pointer are unique_ptr, auto_ptr, shared_ptr, and weak_ptr. Smart pointers are preferable to raw pointers in many different scenarios, but there is still a lot of need to use for the new and delete methods in C++14 and above. When we develop code that requires in-place construction, we need to use new and, possibly, delete operations. They are useful, in a memory pool, as an allocator, as a tagged variant, as a buffer, or as a binary message to a buffer. Sometimes we can use new and delete for some containers if we want to use raw pointers for storage. Modern C++ has a lot of modern choices for faster and safer memory operations. Generally, developers choose to use unique_ptr/make_unique and make_shared rather than raw calls to new and delete. Even though we have a lot of standard smart pointers and abilities, we still need new and/or delete operators. How can we use new and delete elisions in C++? What is the new operator in C++? The new operator in C++, denotes a request for memory allocation on the free memory. If there is sufficient memory, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.    = new ;   Here, the data_type could be any built-in data type, i.e. basic C / C++ types, array, or any class types i.e. class, structure, union.  Now, let’s see how we can use new operator. We can simply use auto and new to create a new pointer and space for its buffer as below,   auto *ptr = new long int;     or in old style still you can use its type in definition instead of auto as below,   long int *ptr = new long int;     one of the great feature of pointers is we don’t need to allocate them at the beginning, we can set them NULL, and we can allocate them in some steps as below,   long int *ptr = NULL; … ptr = new long int;     What is the delete operator in C++? The delete operator in C++ is used to free the dynamically allocated array pointed by pointer variable. Here is the syntax for the delete operator,   delete ;   we can use delete[] for the pointer_arrays, here is the syntax for them,   delete[] ;   here is how we can use delete to delete a pointer, and this is how we can delete pointer arrays,   int *arr […]

Read More

What Is make_unique And How To Use With unique_ptr In C++

Allocating memory and freeing it safely is hard if you are programming a very big application. In Modern C++ there are smart pointers that help avoid the mistake of incorrectly freeing the memory addressed by pointers. Smart pointers make it easier to define and manage pointers, they came with C++11. The most used types of C++ smart pointer are unique_ptr, auto_ptr, shared_ptr, and weak_ptr. In C++14, there is make_unique (std::make_unique) that can be used to allocate memory for the unique_ptr smart pointers. What is a smart pointer and what is unique_ptr in C++? In computer science, all data and operations during runtime are stored in the memory of our computation machines (computers, IoTs, or other microdevices). This memory is generally RAM (Random Access Memory) that allows data items to be read or written in almost the same amount of time, irrespective of the physical location of data inside the memory. Allocating memory and freeing it safely is really hard if you are programming a very big application. C and C++ were notorious for making this problem even more difficult since earlier coding styles and C++ standards had fewer ways of helping developers deal with pointers and it was fairly easy to make a mistake of manipulating a pointer which had become invalid. In Modern C++, there are smart pointers that help avoid the mistake of incorrectly freeing the memory addressed by pointers which was often the source of bugs in code which could often be difficult to track down. Smart pointers make it easier to manage pointers, they came with the release of the C++11 standard. The most used types of C++ smart pointer are unique_ptr, auto_ptr, shared_ptr, and weak_ptr. std::unique_ptr is a smart pointer that manages and owns another object with a pointer, when the unique_ptr goes out of scope C++ disposes of that object automatically. If you want to do some magic in memory operations use std::unique_ptr. Here are more details on how you can use unique_ptr in C++, What is std::make_unique in C++? The std::make_unique is a new feature that comes with C++14. It is used to allocate memory for the unique_ptr smart pointers, thus managing the lifetime of dynamically allocated objects. std::make_unique template constructs an array of the given dynamic size in memory, and these array elements are value-initialized. Since C++14 to C++20, the std::make_unique function is declared as a template as below,   template unique_ptr make_unique( std::size_t size );     template unique_ptr make_unique( Args&&… args );   The std::make_unique function does not have an allocator-aware counterpart; it returns unique_ptr which would contain an allocator object and invoke both destroy and deallocate in its operator(). How to use std::make_unique with std::unique_ptr in C++? Let’s assume you have a simple class named myclass, We can create a unique pointer (a smart pointer) with this class as below,   std::unique_ptr p = std::make_unique();   Or it can be used with struct as below:   struct st_xy {     int x,y; };   We can create a unique pointer as we illustrate in the example below.   std::unique_ptr xy = std::make_unique();   We can use the auto keyword and we can define the maximum array elements like so:   auto ui = std::make_unique(5);   What are the advantages to use std::make_unique in C++? The std::make_unique function is useful when allocating smart pointer, because: We don’t need to think about new/delete or new[]/delete[] elisions. When […]

Read More

How To Use std::exchange In C++

C++ is a very precise programming language that allows you to use memory operations in a wide variety of ways. Mastering efficient memory handling will improve your app performance at run time and can result in faster applications that have optimal memory usage. One of the many useful features that come with the C++14 standard is the std::exchange algorithm that is defined in the utility header. In this post, we explain how to use std::exchange in C++. What is std::exchange in C++? The std::exchange algorithm is defined in the header and it is a built-in function that comes with C++14. The std::exchange algorithm copies the new value to a given object and it will return the old value of that object. Here is the template definition syntax (since C++14, until C++20):   template T exchange( T& object, U&& new_value );   How to use std::exchange in C++? We can use std::exchange to exchange variables values as below, and we can obtain old value from the return value of std::exchange.   int x = 500; int y = std::exchange(x, 333);   After these lines, x is now 333 and y is the old value of x , 500. We can use std::exchange to set values of object lists (i.e vectors) as shown below:   std::vector vec; std::exchange( vec, { 10, 20, 30, 40, 50 } );   In addition, we can copy old values to another object list as we show in the following example:   std::vector vec, vec0; vec0 = std::exchange( vec, { 10, 20, 30, 40, 50 } );   We can use std::exchange to change function definitions too, for example assume we have myf1() function, now we want to exchange myf() function to myf1() function, this is how we can do:   void (*myf)(); std::exchange(myf, myf1); // myf is now myf1 myf();   Is there a full example of how to use std::exchange in C++? Here is a full example of how to use std::exchange in C++. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46   #include #include   void myf1() { std::cout

Read More

Open Sourcing IFC SDK for C++ Modules

Open Sourcing IFC SDK for C++ Modules GDR October 3rd, 20234 3 Back with VS2019 version 16.10, we announced a complete implementation of C++ Modules (and, generally, of all C++20 features) across the MSVC compiler toolset, static analysis, IntelliSense, and debugger. Implementing Modules requires principled intermediate representation of C++ source programs. Today, we are thrilled to announce the availability of the IFC SDK, a Microsoft implementation of the IFC Specification. This is an open-source project under the Apache 2-with-LLVM-exception license. The IFC Specification formalizes C++ programs as data amenable to semantics-based manipulation. We are open sourcing the IFC SDK in the hope of accelerating widespread use and implementation of C++ Modules across the C++ community and the C++ tools ecosystem. What Is an IFC and What Is It Good for? A popular compilation strategy of a C++ Module interface (or header unit) source file is to translate the source file, exactly once, into an internal representation suitable for reuse in other source files. That intermediate form is generally referred to as a Built Module Interface (BMI). An IFC file is an implementation of the BMI concept. An IFC file is a persistent representation of all information pertaining to the semantics of a C++ program. In addition to direct use by compilers to implement C++ Modules, an IFC can also be inspected by non-compiler tools for semantics-based exploration of C++ source files. Such tools are useful for explorers in understanding how C++ source-level constructs can be represented in a form suitable for C++ Modules implementation. IFC SDK Scope The IFC SDK is currently an experimental project. It focuses on providing datatypes and source code supporting the read and write of IFC files. This SDK is the same tested implementation used in the MSVC compiler front-end to implement C++ Modules.  Consequently, while the GitHub OSS repo is “experimental”, the code is far from it. Those datatypes can be memory-mapped directly for scalable and efficient processing. The project also features utilities for formatting or viewing IFC files. We welcome, and we are looking for, contributions that fix gaps between the SDK and the Specification, and for changes required to support C++ standards starting from C++20 and upwards. Call to Action We encourage you to check out the IFC SDK repo, build it, experiment with it, and contribute. We would like to hear from you. If you’re a C++ compiler writer interested in supporting the IFC file format, please reach out at the IFC Specification repo and share feedback, suggestions, or bug fixes.  You can also reach us on Twitter (@VisualC), or via email at visualcpp@microsoft.com.   GDR Software Architect, DevDiv Follow

Read More

Build Reliable and Secure C++ programs — Microsoft Learn

Build Reliable and Secure C++ programs — Microsoft Learn Herb Sutter October 2nd, 20230 1 “The world is built on C and C++” is no overstatement — C and C++ are foundational languages for our global society and are always in the world’s top 10 most heavily used languages now and for the foreseeable future. Visual Studio has always supported many programming languages and we encourage new languages and experiments; diversity and innovation are healthy and help progress the state of the art in software engineering. In Visual Studio we also remain heavily invested long-term in providing the best C and C++ tools and continuing to actively participate in ISO C++ standardization, because we know that our internal and external customers are relying on these languages for their success, now and for many years to come. As cyberattacks and cybercrimes increase, we have to defend our software that is under attack. Malicious actors target many attack vectors, one of which is memory safety vulnerabilities. C and C++ do not guarantee memory safety by default, but you can build reliable and secure software in C++ using additional libraries and tools. And regardless of the programming languages your project uses, you need to know how to defend against the many other attack vectors besides memory safety that bad actors are using daily to attack software written in all languages. To that end, we’ve just published a new document on Microsoft Learn to help our customers know and use the tools we provide in Visual Studio, Azure DevOps, and GitHub to ship reliable and secure software. Most of the advice applies to all languages, but this document has a specific focus on C and C++. It was coauthored by many subject-matter experts in programming languages and software security from across Microsoft: Build reliable and secure C++ programs | Microsoft Learn This is a section-by-section companion to the United States government publication NISTIR 8397: Guidelines on Minimum Standards for Developer Verification of Software. NISTIR 8397 contains excellent guidance on how to build reliable and secure software in any programming language, arranged in 11 sections or topics. For each NISTIR 8397 section, this Learn document summarizes how to use Microsoft developer products for C++ and other languages to meet that section’s security needs, and provides guidance to get the most value in each area. Most of NISTIR 8397’s guidance applies to all software; for example, all software should protect its secrets, use the latest versions of tools, do automated testing, use CI/CD, verify its bill of materials, and so on. But for C++ memory safety specifically, see our Learn document’s information in sections 2.3, 2.5, and 2.9 for a detailed list of analyses (e.g., CodeQL, Binskim, /analyze), safe libraries (e.g., GSL, SafeInt), hardening compiler switches (e.g., /sdl, /GS, /guard, /W4, /WX, /Qspectre), and tools (e.g., Address Sanitizer, LibFuzzer) that your project can and should use regularly to harden your C++ programs. If your project uses C++ and you find items listed that you’re not using yet, don’t wait — start adding them to your project today! Safety and security are essential. We want to help all of our customers to know about and use the state-of-the-art tools we provide in Visual Studio, Azure DevOps, and GitHub for writing reliable and secure software in our device-and-cloud […]

Read More

What Are The Relaxed Constexpr Restrictions In C++?

In C++, the constexpr specifier is used to declare a function or variable to evaluate the value of at compile time, which speeds up code during runtime. This useful property had some restrictions in C++11, these are relaxed in C++14 and this feature is known as Relaxed Constexpr Restrictions. In this post, we explain what are the relaxed constexpr restrictions in modern C++. What is the constexpr specifier in modern C++? The C++11 standard comes with the introduction of generalized constexpr functions. The constrexpr is used as a return type specifier of function and improves performance by computations done at compile time rather than run time. Return values of constexpr could be consumed by operations that require constant expressions, such as an integer template argument. Here is the syntax:   constexpr   Here is an example of how to use a constexpr in C++:   constexpr double sq(const double x) { return ( x*x ); }   and can be used as shown below.   constexpr double y = sq(13.3);   Note that here we used a constant variable 13.3, that is given in coding, thus the result y will be calculated during compilation as 176.89. Then, we can say, similarly this line will be compiled as we show below:   const double y = 176.89   Is there a simple constexpr specifier example in modern C++? Here we can sum all above in an example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18   #include   // C++11, a simple constexpr example constexpr double sq(const double x) { return ( x*x ); }   int main() { constexpr double y = sq(13.3); std::cout

Read More

MSVC ARM64 Optimizations in Visual Studio 2022 17.7

MSVC ARM64 Optimizations in Visual Studio 2022 17.7 Hongyon Suauthai (ARM) September 28th, 20230 2 In Visual Studio 2022 version 17.6 we added a host of new ARM64 optimizations. In this 2nd edition of our blog, we will highlight some of the performance improvements to MSVC ARM64 compiler backend, we will discuss key optimizations in the Visual Studio 2022 version 17.7 for both scalar ISA and SIMD ISA (NEON). We started introducing these performance optimizations in 17.6 release and we have landed them in 17.7 release. By element operation ARM64 supports by-element operation in several instructions such as fmul, fmla, fmls, etc.  This feature allows a SIMD operand to be computed directly by a SIMD element using an index to access it. In the example below where we multiply a scalar with an array, MSVC duplicated the vector element v0.s[0] into all lanes of a SIMD register, then multiplied that with another SIMD operand represented by array b.  This is not efficient because the dup instruction will add 2 more execution latency before executing the fmul instruction. To better understand this optimization let’s take the following sample code: void test(float * __restrict a, float * __restrict b, float c) {   for (int i = 0; i < 4; i++)        a[i] = b[i] * c; } Code generated by MSVC 17.6:        dup         v17.4s,v0.s[0]        ldr         q16,[x1]        fmul        v16.4s,v17.4s,v16.4s         str         q16,[x0] In Visual Studio 2022 17.7, we eliminated a duplicate instruction. It now can multiply by a SIMD element directly and the code generation is:        ldr         q16,[x1]        fmul        v16.4s,v16.4s,v0.s[0]         str         q16,[x0] Neon supports for shift right and accumulate immediate This instruction right-shifts a SIMD source by an immediate and accumulates the final result with the destination SIMD register. As mentioned earlier, we started working on this optimization in the 17.6 release and completed the feature in the 17.7 release. In the 17.5 release MSVC turned right shifts into left shifts using a negative shift amount. To implement it that way, it copied a constant -2 into a general register, and then duplicated a general register into the SIMD register before the left shift. We eliminated the duplicate instruction and used right shift with an immediate value in the 17.6 release. It was an improvement, but not yet good enough. We further improved the implementation in 17.7 by combining right shift and add by using usra for unsigned and ssra for signed operation. The final implementation is much more compact than the previous ones. To better understand how this optimization works let’s look at the sample code below: void test(unsigned long long * __restrict a, unsigned long long * __restrict b) {    for (int i = 0; i < 2; i++)        a[i] += b[i] >> 2; } Code generated by MSVC 17.5:        mov         x8,#-2        ldr         q16,[x1]        dup         v17.2d,x8        ldr         q18,[x0]        ushl        v17.2d,v16.2d,v17.2d        add         v18.2d,v17.2d,v18.2d         str         q18,[x0] Code generated by MSVC 17.6:        ldr         q16,[x1]        ushr        v17.2d,v16.2d,#2        ldr         q16,[x0]        add         v16.2d,v17.2d,v16.2d         str         q16,[x0] Code generated by MSVC 17.7:        ldr         q16,[x0]        ldr         q17,[x1]        usra        v16.2d,v17.2d,#2         str         q16,[x0] Neon right shift into cmp A right shift on a signed integer shifts the msb, with the result being either -1 or 0, and […]

Read More

Microsoft C++ Team at CppCon 2023

Microsoft C++ Team at CppCon 2023 Sy Brand September 28th, 20230 2 As always our team will be at CppCon this year with a host of presentations. Many of us will also be present at our team’s booth in the main hall for the first two days of the conference. Come say hi and let us know if you have any questions about our talks, products, or anything else! You can also join the #visual_studio channel on the CppCon Discord to talk to us (note: to join, head to #directory channel first, and check the checkbox next to “Visual Studio” box). We’re also running a survey on the C++ ecosystem. If you have a moment, please take our survey. It’s quick and you could win a utility backpack or duffel bag. Here’s the lineup: Monday 2nd​ Lifetime Safety in C++ – Gabor Horvath – 11am ​ Informal Birds of a Feather for Cpp2/cppfront – Herb Sutter – 12:30pm​ Tuesday​ 3rd​ What’s New in Visual Studio – David Li & Mryam Girmay – 3:15pm​ ​Thursday 5th​​ Cooperative C++ Evolution: Towards a Typescript for C++ – Herb Sutter (Keynote) – 10:30am​ How Visual Studio Code Can Help You Develop More Efficiently in C++ – Alexandra Kemper & Sinem Akinci – 3:15pm​ Regular, Revisited – Victor Ciura – 3:15pm​ Friday 6th​​ Getting Started with C++ – Michael Price – 1:30pm   Sy Brand C++ Developer Advocate, C++ Team Follow

Read More

Useful Features Of Modern C++ That Come With C++14

Hello fellow C++ Developers. This week we continue to explore features from the C++14 standard. One of the features that comes with C++14 is auto return type deduction,. We explain auto return type deduction with very simple examples including lambda and template examples. The Lambda Expression construct is introduced in C++ 11 and further developed in the C++14, C++17, and C++20 standards. In C++14, lambda expressions are improved by the generalized lambda (generic lambda) and we explain how you can use generalized lambda captures in modern C++. Our educational LearnCPlusPlus.org site has a broad selection of new and unique posts with examples suitable for everyone from beginners to professionals alike. It is growing well thanks to you, and we have many new readers, thanks to your support! The site features a plethora of posts that are great for learning the features of modern C++ compilers with very simple explanations and examples. RAD Studio’s C++ Builder, Delphi, and their free community editions C++ Builder CE, and Delphi CE are powerful tools for modern application development. Table of Contents Where I can I learn C++ and test these examples with a free C++ compiler? How to use modern C++ with C++ Builder? How to learn modern C++ for free using C++ Builder? Do you want to know some news about C++ Builder 12? Where I can I learn C++ and test these examples with a free C++ compiler? If you don’t know anything about C++ or the C++ Builder IDE, don’t worry, we have a lot of great, easy to understand examples on the 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 type of post. 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 articles with very simple examples that can be used with: The free version of C++ Builder 11 CE Community Edition or a professional version of C++ Builder  or free BCC32C C++ Compiler and BCC32X C++ Compiler or the free Dev-C++ Read the FAQ notes on the CE license and then simply fill out the form to download C++ Builder 11 CE. How to use modern C++ with C++ Builder? C++11 allowed lambda functions to deduce the return type based on the type of the expression given to the return statement. The C++14 standard provides return type deduction in all functions, templates, and lambdas. C++14 allows return type deduction for functions that are not of the form return expressions. In this post, we explain the auto keyword, what is an auto type deduction, and how we can use it in functions, templates, and lambdas. In the first post, explain what is auto return type deduction. Lambda Expressions allow users to write an inline expression that can be used for short snippets of code in your C++ app which are not going to be reused and don’t require naming. The Lambda Expression construct is introduced in C++ 11 and further developed in the C++14, C++17, and C++20 standards. In C++14, lambda expressions are improved by the generalized lambda (generic lambda) or initialized lambda feature, and in the next post, we remember what lambda is and explain what a generic lambda is, and how we can use it. C++14 standard […]

Read More

Announcing the new updated RAD Server Technical Guide

Back in 2019, David I wrote a fantastic guide to RAD Server that has been very popular in helping developers develop new, and migrate older systems towards a RESTful architecture. There have been a number of updates to RAD Server since the guide was originally launched, including a number of new components that have simplified and made RAD Server even more RAD!  We have also had a lot of feedback over time about using the guide, and we have incorporated a large part of that into the new, heavily revised version. Today we launch the first part of that guide but with a refreshed approach. Now you will find not only the text guide but also source code examples that you can directly download from Github for both Delphi and C++Builder, and also includes a comprehensive video series supporting each chapter.  To download the latest RAD Server Technical Guide for Free, just click the next button: Download guide Once you have downloaded the new guide, you will find in the paper the links for the GitHub repository with all the examples as well as the video series included. The list of the current published chapters is: Chapter 1: What’s RAD Server – IntroductionChapter 2: Using the RAD Wizard to Create a “hello world”Chapter 3: Creating your first CRUD ApplicationChapter 4: REST DebuggerChapter 5: Using FireDAC Batch Move and JSONWriterChapter 6: JSONValue, JSONWriter and JSONBuilderChapter 7: Creating your own customized endpointsChapter 8: Accessing the built-in analyticsChapter 9: Deploying RAD Server (Windows, Linux & Docker)Chapter 10: RAD Server Lite Our plan is to keep this guide updated and release new chapters progressively in the future so stay tuned for upcoming updates. Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder. Design. Code. Compile. Deploy. Start Free Trial   Upgrade Today    Free Delphi Community Edition   Free C++Builder Community Edition

Read More