Noutați

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

How Event-Driven Architectures Drive Real-Time Operations

People, events, the human brain—in fact, the whole world operate in real-time, but businesses have struggled to keep up. With the help of event-driven architecture (EDA) and the Open API economy, businesses can now do the same. The power of an event-driven world means that, after years of geopolitical events affecting how businesses operate, many businesses are starting to uncover real value by truly being able to operate in real-time. Whether it be retail and manufacturing or energy and resources and financial services, locating and responding to vital issues within a company’s supply chains or product lines in real-time, is key to success. Amazon’s CTO, Dr. Werner Vogels, said that “the world is event driven” in his keynote speech at AWS re:Invent in December 2022. Now, new IDC research unveils that nine out of 10 of the world’s largest companies will deploy real-time intelligence driven by event-streaming technologies by 2025. But What’s the Secret Behind Such Success? A recent IDC Infobrief, sponsored by Solace, surveyed over 300 enterprise IT professionals in North America, Asia and Europe, all of whom work for large companies implementing or considering EDA. The results are quite telling–an overwhelming 93% of respondents at companies that have deployed EDA across multiple use cases said EDA has either met or exceeded their expectations. In addition to technical advantages from EDA, most businesses also see clear business benefits: A full 23% of respondents reported increasing productivity; 22% said better customer acquisition and 18% saw revenues increase as a result of EDA efforts. 1. Get Support From the Top to Ensure Alignment Throughout Expanding the footprint of EDA across the enterprise is a journey, and every journey starts by assembling those that are critical to its overall success. Business sponsorship and engaging key stakeholders is vital, especially in the early days of EDA adoption – 56% of respondents in the early EDA stages cited this as a priority when ROI and business benefits may not be immediately clear. The impact of well-aligned C-suite, operational and technical teams is reflective of business-level digital maturity, too. As 35% of respondents at an advanced stage of EDA rollout felt C-level support was critical, it comes as no surprise that respondents with higher levels of EDA maturity also have higher levels of overall digital maturity, including digital strategy and change management support. 2. Tackle Complexities Head-On With the Backing of IT As EDA becomes more pervasive across an organization, demands on IT become more sophisticated, requiring a deepening of EDA skills in the IT organization, notably with DevOps teams, developers and architects. More than one-third (36.1%) of respondents cited the lack of skills to execute EDA as a hurdle to adoption. Approaches to logging, governance and oversight (30.7%) can also become increasingly challenging and must be thought through carefully. This is where EDA providers themselves need to step up and provide adequate training and a certification path for architects DevOps and developers looking to gain the fundamental knowledge and skills to design and implement event-driven systems. This should include technical details such as understanding various design patterns for EDA, microservices choreography versus orchestration, the saga pattern and RESTful microservices. Education should also clearly define and demonstrate key concepts and tools for EDA success, such as event portal, topic hierarchy best practices and event mesh. […]

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

Why AIOps is Critical for Networks

Speaker 1: This is Techstrong TV. Mitch Ashley: With great pleasure of being joined by Andrew Colby. Andrew is VP of AIOps at Vitria. Welcome, Andrew. Andrew Colby: Good afternoon, Mitch. And thank you. Mitch Ashley: It’s a great topic. I’m excited to talk with you about it. We could go down the share war stories in telco experience, which really could be about 10 episodes of a different show, but today in the telco environment, or just in the business environment in general, the economic conditions, competitive pressures, looking for areas where we can get more for less, there are a lot of different parameters that have shifted or changed or maybe tightened that we’re currently working within. I’d love to get your perspective on that. Andrew Colby: Certainly, and thank you. Yeah, I’d say we see cautious optimism. Obviously, I’m based in the US in the DC Metro area, Maryland. And the US, the government entities and quasi-governmental entities have been tightening the economic structure in order to tame inflation. Fortunately, that has not driven our economy and had the potential recessionary effect that was feared, but people are still cautious, businesses are still cautious. That said, it’s hard to hire people and it’s really hard to hire technical people. So a lot of companies are continuing to look towards how to leverage technologies and automation to build efficiency so that they can do more with either the same number of people or re-task their people to higher value purposes, and let the technology do some of the more menial and mundane tasks. And we can explore this a little bit, especially in these new complex service delivery and network environments. It’s very difficult for me to imagine how an engineer who’s gone through anywhere from two to eight years of college education is going to really be happy going and spending their days collecting a lot of data across network, container management VM and other infrastructure systems to figure out what’s going on. I mean, really that’s where a lot of the automation provides a significant amount of value to let the engineers do the smart, difficult things that we want humans to do. Mitch Ashley: And a lot of pressures around meantime to recovery, even looking at resiliency, how do we stand up under a test-full situation, whether it be a security attack that might be going on or some unobserved condition that our systems and networks have never been under? Andrew Colby: Oh, there’s so much of that. So much is changing. It’s not just a person like you or me behind a smartphone that can actually report that there’s a problem, but it’s sensors and equipment that won’t necessarily report right away, so it needs to be detected. So that’s a whole nother additional dimension that service providers, large enterprise IT organizations are under, which is to be able to have this kind of real-time awareness of what’s going on. Whether the service is real time, like the video conference that we’re on or not, there really is a desire and expectation to have real time awareness of the service delivery to be able to detect what’s going on, react to it, address it before the user, whoever that is, the customer, the employee […]

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