C++ Builder

What Is std::quoted Quoted String In Modern C++?

Sometimes we want to preserve the string format especially when we use string in a string with /”. In C++14 and above, there is a std::quoted template that allows handling strings safely where they may contain spaces and special characters and it keeps their formatting intact. In this post, we explain std::quoted quoted strings in modern C++. What Is Quoted String In Modern C++? The std::quoted template is included in  header, and it is used to handle strings (i.e. “Let’s learn from ”LearnCPlusPlus.org!” “) safely where they may contain spaces and special characters and it keeps their formatting intact.  Here is the syntax,   std::quoted( )   Here are C++14 templates defined in where the string is used as input,   template quoted( const CharT* s, CharT delim = CharT(‘”‘), CharT escape = CharT(‘\’) );   or   template quoted(   const std::basic_string& s,   CharT delim = CharT(‘”‘), CharT escape = CharT(‘\’) );   Here is a C++14 template defined in where the string is used as output,   template quoted( std::basic_string& s, CharT delim=CharT(‘”‘), CharT escape=CharT(‘\’) );   Note that this feature is is using std::basic_string and it improved in C++17 by the  std::basic_string_view support. What Is std::quoted quoted string in modern C++? Here is an example that uses input string and outputs into a stringstream:   const std::string str  = “I say “LearnCPlusPlus!””; std::stringstream sstr; sstr std::quoted(str_out);  // output sstr to str_out   Is there a full example about std::quoted quoted string in modern C++? Here is a full example about std::quoted in modern 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   #include #include #include   int main() { std::stringstream sstr; const std::string str  = “Let’s learn from “LearnCPlusPlus.org!” “; sstr

Read More

Structured Diagnostics in the New Problem Details Window

Structured Diagnostics in the New Problem Details Window Sy Brand October 11th, 20230 2 Massive compiler errors which seem impossible to navigate are the bane of many C++ developers’ lives. It’s up to tools to provide a better experience to help you comprehend diagnostics and understand how to fix the root issue. I wrote Concepts Error Messages for Humans to explore some of the design space and now, due to the hard work of many folks working on Visual Studio, we have a better experience to share with you all. You can read about some of the work which has led up to these changes in Xiang Fan’s blog post on the future of C++ diagnostics in MSVC and Visual Studio. In Visual Studio 2022 version 17.8 Preview 3, if you run a build using MSVC and an MSBuild project, entries in the Error List which have additional information available will show an icon in a new column named Details: If you click this button, a new Problem Details window will open up. By default this will be in the same place as the Error List, but if you move it around, Visual Studio will remember where you put it. This Problem Details window provides you with detailed, structured information about why a given problem occurred. If we look at this information we might think, okay, why could void pet(dog) not be called? If you click the arrow next to it, you can see why: In a similar way we can expand out other arrows to find out more information about our errors. This example is produced from code which uses C++20 Concepts and the Problem Details window gives you a way to understand the structure of Concepts errors. For those who would like to play around with this example, the code required to produce these errors is: struct dog {}; struct cat {}; void pet(dog); void pet(cat); template concept has_member_pet = requires(T t) { t.pet(); }; template concept has_default_pet = T::is_pettable; template concept pettable = has_member_pet or has_default_pet; void pet(pettable auto t); struct lizard {}; int main() { pet(lizard{}); } Make sure you compile with /std:c++20 to enable Concepts support. Output Window As part of this work we have also made the Output Window visualize any hierarchical structure in the output diagnostics. For example, here in an excerpt produced by building the previous example: 1>Source.cpp(18,6): 1>or ‘void pet(_T0)’ 1>Source.cpp(23,5): 1>the associated constraints are not satisfied 1> Source.cpp(18,10): 1> the concept ‘pettable’ evaluated to false 1> Source.cpp(16,20): 1> the concept ‘has_member_pet’ evaluated to false 1> Source.cpp(10,44): 1> ‘pet’: is not a member of ‘lizard’ 1> Source.cpp(20,8): 1> see declaration of ‘lizard’ 1> Source.cpp(16,41): 1> the concept ‘has_default_pet’ evaluated to false 1> Source.cpp(13,30): 1> ‘is_pettable’: is not a member of ‘lizard’ 1> Source.cpp(20,8): 1> see declaration of ‘lizard’ This change makes it much easier to scan large sets of diagnostics without getting lost. Code Analysis The Problem Details window is now also used for code analysis warnings which have associated Key Events. For example, consider this code which could potentially result in a use-after-move: #include void eat_string(std::string&&); void use_string(std::string); void oh_no(bool should_eat, bool should_reset) { std::string my_string{ “meow” }; bool did_reset{ false }; if (should_eat) { eat_string(std::move(my_string)); } if (should_reset) { did_reset = true; my_string = “the string is reset”; } […]

Read More

What Is Decltype (auto) In Modern C++ And How To Use It?

The auto keyword arrives with the new features of the C++11 and the standards above. In C++14, there is a new decltype that is used with auto keyword. In modern C++, the decltype(auto) type-specifier deduces return types while keeping their references and cv-qualifiers, while auto does not. In this post, we explain what decltype (auto) is in modern C++ and how to use it. What is auto in modern C++? The auto keyword is used to define variable types automatically, it is a placeholder type specifier (an auto-typed variable), or it can be used in a function declaration, or a structured binding declaration. If you want to learn more about auto keyword, here it is, What is decltype in modern C++? The decltype keyword and operator represents the type of a given entity or expression. This feature is one of the C++11 features added to compilers (including BCC32 and other CLANG compilers). In a way you are saying “I am declaring this variable to be the same type as this other variable“. Here are more details about how you can use it, How to use decltype (auto) in modern C++? In C++14, there is a new decltype feature that allows you to use with the auto keyword. In C++14 and standards above, the decltype(auto) type-specifier deduces return types while keeping their references and cv-qualifiers, while auto does not. Since C++14, here is the syntax,   type_constraint (optional) decltype ( auto )   In this syntax, the type is decltype(expr) and expr can be an initializer or a return statement. Here is a simple example how we can use it,   decltype(auto) x = i;   Are there some simple examples about decltype (auto) in modern C++? Here are some simple examples that shows difference between auto and decltype(auto), In C++14 and above, we can use decltype(auto) with const int values as below,   const int x = 4096; auto xa = x;    // xa : int decltype(auto) xb = x;  // xb : const int   In C++14 and above, we can use decltype(auto) with int& values as below,   int y = 2048; int& y0 = y;  // y_ : int auto ya = y0;  // yc2 : int decltype(auto) yb = y0;  // yb : int&   In C++14 and above, we can use decltype(auto) with int values as below,   int&& z = 1024; auto zm = std::move(z);   // zm : int decltype(auto) zm2 = std::move(z);  // zm2 : int&&   In C++11 and above, we can use auto for return types,   auto myf(const int& i) { return i; // auto return type : int }   In C++14 and above, we can use decltype(auto) for return types,   decltype(auto) myf2(const int& i) {    return i; // decltype(auto) return type : const int& }   Is there a full example about decltype (auto) in modern C++? Here is a full example that shows how you can use auto and decltype(auto) in different int types. 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 47 48 49 50 51 52 53 54   #include   auto myf(const int& i) { return i; // auto […]

Read More

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