This document provides an overview of the C++ Boot Camp for CSE 380. It includes:
- A disclaimer that the presenter is not the grader and their opinions are their own.
- An outline of topics to be covered in the boot camp over two weeks, including basic C++ syntax like if/else statements, loops, functions, pointers, references, classes and inheritance.
- Code snippets demonstrating many of these basic C++ concepts like main program structure, preprocessor directives, exceptions, constructors and destructors.
This is a small note on the results of checking the OpenSSL project with the PVS-Studio analyzer. I analyzed the openssl-0.9.8-stable-SNAP-20121208 version.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
Operating systems are among the largest and most complicated software projects, and that means they perfectly suit the purpose of demonstrating static code analysis' capabilities. After the successful analysis of Linux Kernel, I felt inspired to try analyzing other open-source operating systems as well.
Python and Ruby implementations compared by the error densityPVS-Studio
Which programming language to start learning? Python or Ruby? Which one is better? Django or Ruby on Rails? Such questions can often be found on IT forums around the world. I suggest comparing not the languages themselves, but their reference implementations: CPython and MRI. In this article, we are going to cover the errors that were found by PVS-Studio in these projects.
Dusting the globe: analysis of NASA World Wind projectPVS-Studio
Sometimes it is useful to look back to see how helpful the analyzer was to old projects, and which errors can be avoided in good time, if the analyzer is regularly used. This time our choice was NASA World Wind project, which was being developed on C# until 2007.
This is targeted to be a short tutorial for familiarising the new programming concepts introduced in Java 1.7 or Java 7.0 I contains working code snippets to familiarise with new syntax as well.... Hope you will like it !!!!
h
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
ChakraCore: analysis of JavaScript-engine for Microsoft EdgePVS-Studio
On the JSConf US conference in December 2015 the developers announced that they were planning to make open the source code of Chakra key components, a JavaScript-engine, operating in Microsoft Edge. Recently the ChackraCore source code became available under the MIT license in the corresponding repository on GitHub. In this article you will find interesting code fragments that were detected with the help of PVS-Studio code analyzer.
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseAndrey Karpov
CppCat was used to analyze the source code of the OpenMW project, which aims to recreate the Elder Scrolls game Morrowind with open source code. CppCat found 12 fragments of suspicious code in OpenMW, including potential array overruns, redundant clear calls, infinite loops, null pointer issues, and logical errors. Analyzing source code with CppCat can help eliminate bugs and save development time.
This is a small note on the results of checking the OpenSSL project with the PVS-Studio analyzer. I analyzed the openssl-0.9.8-stable-SNAP-20121208 version.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
Operating systems are among the largest and most complicated software projects, and that means they perfectly suit the purpose of demonstrating static code analysis' capabilities. After the successful analysis of Linux Kernel, I felt inspired to try analyzing other open-source operating systems as well.
Python and Ruby implementations compared by the error densityPVS-Studio
Which programming language to start learning? Python or Ruby? Which one is better? Django or Ruby on Rails? Such questions can often be found on IT forums around the world. I suggest comparing not the languages themselves, but their reference implementations: CPython and MRI. In this article, we are going to cover the errors that were found by PVS-Studio in these projects.
Dusting the globe: analysis of NASA World Wind projectPVS-Studio
Sometimes it is useful to look back to see how helpful the analyzer was to old projects, and which errors can be avoided in good time, if the analyzer is regularly used. This time our choice was NASA World Wind project, which was being developed on C# until 2007.
This is targeted to be a short tutorial for familiarising the new programming concepts introduced in Java 1.7 or Java 7.0 I contains working code snippets to familiarise with new syntax as well.... Hope you will like it !!!!
h
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
ChakraCore: analysis of JavaScript-engine for Microsoft EdgePVS-Studio
On the JSConf US conference in December 2015 the developers announced that they were planning to make open the source code of Chakra key components, a JavaScript-engine, operating in Microsoft Edge. Recently the ChackraCore source code became available under the MIT license in the corresponding repository on GitHub. In this article you will find interesting code fragments that were detected with the help of PVS-Studio code analyzer.
CppCat Checks OpenMW: Not All is Fine in the Morrowind UniverseAndrey Karpov
CppCat was used to analyze the source code of the OpenMW project, which aims to recreate the Elder Scrolls game Morrowind with open source code. CppCat found 12 fragments of suspicious code in OpenMW, including potential array overruns, redundant clear calls, infinite loops, null pointer issues, and logical errors. Analyzing source code with CppCat can help eliminate bugs and save development time.
This document discusses handling exceptions thrown in C++ constructors. It provides two cases as examples: 1) When an exception is thrown and memory allocated on the stack is destroyed, potentially causing a memory leak. 2) When using smart pointers like shared_ptr avoids this issue by managing memory allocation. The document recommends using smart pointers in modern C++ to prevent memory leaks from exceptions in constructors.
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio
Geant4 project continues developing, so it's really interesting to recheck it with PVS-Studio static code analyzer. This time we'll do a check of version 10.2 (previously, we checked 10.0 beta-version)
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
The document discusses exception handling in C and C++. It covers exception fundamentals, and techniques for handling exceptions in C such as return values, global variables, goto statements, signals, and termination functions. It also discusses exception handling features introduced in C++ such as try/catch blocks and exception specifications.
JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.Jin-Hwa Kim
This document discusses JavaScript closures and prototypes. It provides an example of a closure being created by defining a function within another function that retains access to local variables even after the outer function returns. It also shows how prototypes can be used for inheritance in JavaScript and provides examples of defining Bird and Duck constructor functions and objects that inherit properties and methods. Polymorphism is demonstrated by calling fly() on different bird objects. Use cases for closures include how frameworks like Prototype use closures to bind functions to object contexts.
- Exception handlers immediately follow a try block and are denoted by the catch keyword. Each catch clause handles a single exception type.
- Exception specifications inform users of the types of exceptions a function can throw. They use the throw keyword and appear after a function's argument list.
- The set_unexpected() and set_terminate() functions allow customizing the handlers called for unexpected exceptions and uncaught exceptions, respectively.
Unit Testing in Javascript
The way to quality product isn't easy or simple but it is reachable. One of the key things to do is unit testing. What, when and how to do it --> read in the presentation.
See more details here: http://www.slideshare.net/AnnaKhabibullina/jsfwdays-2014unittesingjavascriptv4-33966202
Read about this and other techtalks @ DA-14 in our blog: http://da-14.com/our-blog/
Just recently I've checked the VirtualDub project with PVS-Studio. This was a random choice. You see, I believe that it is very important to regularly check and re-check various projects to show users that the PVS-Studio analyzer is evolving, and which project you run it on doesn't matter that much - bugs can be found everywhere. We already checked the VirtualDub project in 2011, but we found almost nothing of interest then. So, I decided to take a look at it now, 2 years later.
Handling Exceptions In C & C++ [Part B] Ver 2ppd1961
This document discusses exception handling in C++. It provides an overview of how compilers manage exceptional control flow and how functions are instrumented to handle exceptions. It discusses normal vs exceptional function call flows, and the items involved in stack frames like context, finalization, and unwinding. It also summarizes Meyers' guidelines for exception safety, including using destructors to prevent leaks, handling exceptions in constructors, and preventing exceptions from leaving destructors.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
The document summarizes the author's analysis of the FreeBSD kernel source code using the PVS-Studio static analysis tool. Some key findings include:
1) Over 1000 potential errors were detected by the analyzer, including many typos, copy-paste errors, and issues involving incorrect logical expression evaluations due to operator precedence.
2) Many of the warnings pointed to real bugs, such as identical subexpressions compared using equality operators, equivalent code in "if-else" blocks, and recurring checks of the same condition.
3) Macros were found to cause issues by altering expression evaluation order, highlighting the importance of operator precedence.
4) Examples of specific errors are provided to demonstrate common bugs like
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
As is already known to our readers, PVS-Studio static analyzer is exploring a new development direction - the Linux platform; as you may have noticed from the previous articles, it is doing well. This article shows how easily you can check a project with the help of the Linux version of the analyzer, because the simpler PVS-Studio for Linux is, the more supporters it will have. This time our choice was the CodeLite project. CodeLite was compiled and tested in Linux. Let's see what results we got.
This is the correct article about the results of checking the Geant4 project, which I have written after the previous incorrect one. Let me remind you the whole story. I have recently checked an old version of the Geant4 library and reported the results in the article "Copy-Paste and Muons". Why old version? Nobody is perfect, and we finally made a mistake ourselves. To find out which exactly, see the previous article. This time I offer you a brief report about checking Geant4 of the version 10.0-beta.
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
Cocos2d is an open source software framework. It can be used to build games, apps and other cross-platform GUI based interactive programs. Cocos2d contains many branches with the best known being Cocos2d-Swift, Cocos2d-x, Cocos2d-html5 and Cocos2d-XNA.
In this article, we are going to discuss results of the check of Cocos2d-x, the framework for C++, done by PVS-Studio 5.18. The project is pretty high-quality, but there are still some issues to consider. The source code was downloaded from GitHub.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
The document summarizes the results of re-analyzing the Umbraco codebase with the PVS-Studio static code analyzer one year after its initial analysis. The re-analysis found several new bugs and issues not present in the previous year, indicating that the Umbraco developers addressed the prior year's findings but new errors were introduced with ongoing development. Several interesting new bugs are described involving potential null reference exceptions, off-by-one errors with substring indexing, and incorrect format string usage. Overall the analysis found the code quality to be improved compared to the previous year.
A new static analysis tool for C++ code CppCat was presented just recently. You probably heard a lot about the previous product (PVS-Studio) by the same authors. I was pretty doubtful about it then: on the one hand, static analysis is definitely a must-have methodology - things go better with than without it; on the other hand, PVS-Studio may scare users off with its hugeness, an enterprise-like character and the price, of course. I could imagine a project team of 50 developers buying it but wasn't sure about single developers or small teams of 5 developers. I remember suggesting to the PVS-Studio authors deploying "PVS as a cloud service" and sell access to it by time. But they chose to go their own way and created an abridged version at a relatively small price (which any company or even a single developer can afford).
This document discusses how to safely manage resources like memory in C++ using exception handling and object-oriented patterns. It proposes using a "scoped" class that automatically releases resources when it goes out of scope. This avoids messy try/catch blocks and ensures resources are cleaned up. Later, it expands on scoped to allow transferring ownership between objects, commit/rollback of resources, and returning resources from functions safely. Overall, it presents scoped as a simple but powerful way to automate resource management in C++.
From Elixir to Akka (and back) - ElixirConf Mx 2017Agustin Ramos
From Elixir to Akka (and back)
The document compares the Actor Model as implemented in Elixir and Akka. It discusses key differences in how messages are passed, mailboxes are handled, scheduling works, and monitoring capabilities between the two frameworks. It ultimately concludes that Akka adds unnecessary complexity on top of the JVM compared to Elixir's cleaner implementation of the Actor Model.
El documento describe una plataforma de educación virtual llamada SIVEC diseñada para fortalecer el sistema educativo militar. SIVEC permite la interacción entre estudiantes, profesores e instituciones a través de servicios como mensajería, foros de discusión, videoconferencias y calificaciones de manera segura y amigable. El documento explica las funciones principales de SIVEC como el acceso a contenido educativo, la actualización de perfiles de usuario, el calendario de eventos y los recursos como chat en línea y correo inter
This document discusses a software company that has developed an algorithm and database to help optimize agriculture and biofuel production. It outlines the company's intellectual property strategy, which includes patenting the algorithm and process, trademarking the company name, and keeping the database and software code protected. The company plans to generate revenue through licensing deals and selling access to their agricultural database. Their goals are to continue expanding the database, develop software add-ons, and find additional licensing opportunities for applications of their research.
This document discusses handling exceptions thrown in C++ constructors. It provides two cases as examples: 1) When an exception is thrown and memory allocated on the stack is destroyed, potentially causing a memory leak. 2) When using smart pointers like shared_ptr avoids this issue by managing memory allocation. The document recommends using smart pointers in modern C++ to prevent memory leaks from exceptions in constructors.
PVS-Studio is there to help CERN: analysis of Geant4 projectPVS-Studio
Geant4 project continues developing, so it's really interesting to recheck it with PVS-Studio static code analyzer. This time we'll do a check of version 10.2 (previously, we checked 10.0 beta-version)
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
The document discusses exception handling in C and C++. It covers exception fundamentals, and techniques for handling exceptions in C such as return values, global variables, goto statements, signals, and termination functions. It also discusses exception handling features introduced in C++ such as try/catch blocks and exception specifications.
JavaScript Closures for Dummies & JavaScript prototype, closures and OOP.Jin-Hwa Kim
This document discusses JavaScript closures and prototypes. It provides an example of a closure being created by defining a function within another function that retains access to local variables even after the outer function returns. It also shows how prototypes can be used for inheritance in JavaScript and provides examples of defining Bird and Duck constructor functions and objects that inherit properties and methods. Polymorphism is demonstrated by calling fly() on different bird objects. Use cases for closures include how frameworks like Prototype use closures to bind functions to object contexts.
- Exception handlers immediately follow a try block and are denoted by the catch keyword. Each catch clause handles a single exception type.
- Exception specifications inform users of the types of exceptions a function can throw. They use the throw keyword and appear after a function's argument list.
- The set_unexpected() and set_terminate() functions allow customizing the handlers called for unexpected exceptions and uncaught exceptions, respectively.
Unit Testing in Javascript
The way to quality product isn't easy or simple but it is reachable. One of the key things to do is unit testing. What, when and how to do it --> read in the presentation.
See more details here: http://www.slideshare.net/AnnaKhabibullina/jsfwdays-2014unittesingjavascriptv4-33966202
Read about this and other techtalks @ DA-14 in our blog: http://da-14.com/our-blog/
Just recently I've checked the VirtualDub project with PVS-Studio. This was a random choice. You see, I believe that it is very important to regularly check and re-check various projects to show users that the PVS-Studio analyzer is evolving, and which project you run it on doesn't matter that much - bugs can be found everywhere. We already checked the VirtualDub project in 2011, but we found almost nothing of interest then. So, I decided to take a look at it now, 2 years later.
Handling Exceptions In C & C++ [Part B] Ver 2ppd1961
This document discusses exception handling in C++. It provides an overview of how compilers manage exceptional control flow and how functions are instrumented to handle exceptions. It discusses normal vs exceptional function call flows, and the items involved in stack frames like context, finalization, and unwinding. It also summarizes Meyers' guidelines for exception safety, including using destructors to prevent leaks, handling exceptions in constructors, and preventing exceptions from leaving destructors.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
The document summarizes the author's analysis of the FreeBSD kernel source code using the PVS-Studio static analysis tool. Some key findings include:
1) Over 1000 potential errors were detected by the analyzer, including many typos, copy-paste errors, and issues involving incorrect logical expression evaluations due to operator precedence.
2) Many of the warnings pointed to real bugs, such as identical subexpressions compared using equality operators, equivalent code in "if-else" blocks, and recurring checks of the same condition.
3) Macros were found to cause issues by altering expression evaluation order, highlighting the importance of operator precedence.
4) Examples of specific errors are provided to demonstrate common bugs like
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
As is already known to our readers, PVS-Studio static analyzer is exploring a new development direction - the Linux platform; as you may have noticed from the previous articles, it is doing well. This article shows how easily you can check a project with the help of the Linux version of the analyzer, because the simpler PVS-Studio for Linux is, the more supporters it will have. This time our choice was the CodeLite project. CodeLite was compiled and tested in Linux. Let's see what results we got.
This is the correct article about the results of checking the Geant4 project, which I have written after the previous incorrect one. Let me remind you the whole story. I have recently checked an old version of the Geant4 library and reported the results in the article "Copy-Paste and Muons". Why old version? Nobody is perfect, and we finally made a mistake ourselves. To find out which exactly, see the previous article. This time I offer you a brief report about checking Geant4 of the version 10.0-beta.
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
Cocos2d is an open source software framework. It can be used to build games, apps and other cross-platform GUI based interactive programs. Cocos2d contains many branches with the best known being Cocos2d-Swift, Cocos2d-x, Cocos2d-html5 and Cocos2d-XNA.
In this article, we are going to discuss results of the check of Cocos2d-x, the framework for C++, done by PVS-Studio 5.18. The project is pretty high-quality, but there are still some issues to consider. The source code was downloaded from GitHub.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
The document summarizes the results of re-analyzing the Umbraco codebase with the PVS-Studio static code analyzer one year after its initial analysis. The re-analysis found several new bugs and issues not present in the previous year, indicating that the Umbraco developers addressed the prior year's findings but new errors were introduced with ongoing development. Several interesting new bugs are described involving potential null reference exceptions, off-by-one errors with substring indexing, and incorrect format string usage. Overall the analysis found the code quality to be improved compared to the previous year.
A new static analysis tool for C++ code CppCat was presented just recently. You probably heard a lot about the previous product (PVS-Studio) by the same authors. I was pretty doubtful about it then: on the one hand, static analysis is definitely a must-have methodology - things go better with than without it; on the other hand, PVS-Studio may scare users off with its hugeness, an enterprise-like character and the price, of course. I could imagine a project team of 50 developers buying it but wasn't sure about single developers or small teams of 5 developers. I remember suggesting to the PVS-Studio authors deploying "PVS as a cloud service" and sell access to it by time. But they chose to go their own way and created an abridged version at a relatively small price (which any company or even a single developer can afford).
This document discusses how to safely manage resources like memory in C++ using exception handling and object-oriented patterns. It proposes using a "scoped" class that automatically releases resources when it goes out of scope. This avoids messy try/catch blocks and ensures resources are cleaned up. Later, it expands on scoped to allow transferring ownership between objects, commit/rollback of resources, and returning resources from functions safely. Overall, it presents scoped as a simple but powerful way to automate resource management in C++.
From Elixir to Akka (and back) - ElixirConf Mx 2017Agustin Ramos
From Elixir to Akka (and back)
The document compares the Actor Model as implemented in Elixir and Akka. It discusses key differences in how messages are passed, mailboxes are handled, scheduling works, and monitoring capabilities between the two frameworks. It ultimately concludes that Akka adds unnecessary complexity on top of the JVM compared to Elixir's cleaner implementation of the Actor Model.
El documento describe una plataforma de educación virtual llamada SIVEC diseñada para fortalecer el sistema educativo militar. SIVEC permite la interacción entre estudiantes, profesores e instituciones a través de servicios como mensajería, foros de discusión, videoconferencias y calificaciones de manera segura y amigable. El documento explica las funciones principales de SIVEC como el acceso a contenido educativo, la actualización de perfiles de usuario, el calendario de eventos y los recursos como chat en línea y correo inter
This document discusses a software company that has developed an algorithm and database to help optimize agriculture and biofuel production. It outlines the company's intellectual property strategy, which includes patenting the algorithm and process, trademarking the company name, and keeping the database and software code protected. The company plans to generate revenue through licensing deals and selling access to their agricultural database. Their goals are to continue expanding the database, develop software add-ons, and find additional licensing opportunities for applications of their research.
5 слов об общении в интернете на английском языке - chatterRuslan Lyashchuk
Как можно общаться в интернете и социальных сетях на английском языке используя сокращения. Сокращенные слова на английском языке для удобства общения в интернете.
O documento discute uma proposta para uma nova Instrução Normativa (IN) para o Sistema Brasileiro de Rastreabilidade da Cadeia Produtiva de Bovinos e Bubalinos (SISBOV). A proposta introduz o "agente certificador autônomo", que poderia criar conflitos de interesse, e reduz os requisitos de rastreabilidade individual dos animais. As certificadoras credenciadas argumentam que a IN-17 vigente deve ser mantida, com melhorias, em vez de substituída, para preservar a qualidade e credibilidade do sistema.
This document summarizes an article about the 5 best performing technology ETFs in November. The top 5 are KraneShares CSI China Internet Fund (KWEB), Guggenheim China Technology ETF (CQQQ), EMQQ Emerging Markets Internet & Ecommerce ETF (EMQQ), PowerShares NASDAQ Internet ETF (PNQI), and Global X NASDAQ China Technology ETF (QQQC). These ETFs had strong 1-month returns ranging from 14.2% to 20.7%, driven by gains in major Chinese technology companies like Tencent, Alibaba, and Baidu. However, these ETFs remain relatively small with assets under $150 million, compared
The document provides an overview of Box2D physics engine conventions and best practices, including how to work with bodies, fixtures, joints, forces, collisions, queries, and loading RUBE worlds. Key recommendations are to use forces over manual positioning, implement debug drawing, and leverage filters to control specific collisions.
This Haiku Deck presentation contains photos from various photographers including erix, sake028, eclectic echoes, sweetbeetandgreenbean, Abdulrahman BinSlmah, and Horatiu Curutiu. It encourages the viewer to get started creating their own Haiku Deck presentation on SlideShare.
Phylogenetics of the grass family (poaceae)Vishnu Mohanan
This document summarizes a study on the phylogenetics of the grass family (Poaceae). DNA sequences were collected from 18 grass species to analyze relationships at the generic level and investigate asymmetry in phylogenies. Well-resolved trees placed bamboos as a monophyletic tribe and showed that woodiness likely evolved independently multiple times with the ancestral bamboo likely being herbaceous. However, conflicts with other studies were found that require further sampling. Issues with DNA degradation from plant storage were also noted.
This document discusses the key components of weather and climate. It describes the atmosphere as being made up of four layers - the troposphere, stratosphere, mesosphere, and thermosphere. The ozone layer, located in the stratosphere, protects the Earth from harmful ultraviolet radiation. Temperature varies based on factors like latitude, altitude, and distance from bodies of water. Humidity and precipitation are also influenced by temperature, with water vapor condensing into clouds and precipitating as rain, snow, or hail. Atmospheric pressure changes with temperature and altitude, and wind is caused by differences in air pressure.
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
This document discusses functions and header/source files in C++. It covers declarations, definitions, and the differences between them. Declarations introduce names and specify types, while definitions also fully specify the entity. Declarations allow interfaces to be specified. Headers contain declarations to share interfaces between parts of a program. Functions are described as units of operation that can take parameters and return values. The document also discusses scopes, namespaces, and storage classes like static.
The document discusses the C++ Core Guidelines and the Guideline Support Library. The Core Guidelines provide rules for writing good C++ code that avoids crashes, undefined behavior, and other issues. The Guideline Support Library (GSL) implements concepts, types and functions that support following the guidelines. Examples of guidelines include using RAII to avoid resource leaks, preferring compile-time checking over runtime checking, keeping interfaces strongly typed, and avoiding unnecessary heap allocations. Tools like CppCoreCheck and clang-tidy can check code for adherence to the guidelines.
••• Boost your code's performances using C++11 new features! •••
In this presentation you will learn:
▸ the difference between an Lvalue and Rvalue
▸ how to use std::move, std::forward, noexcept
▸ how to implement move semantics to avoid useless copies
▸ how to implement perfect forwarding for the factory pattern
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
Whether you program regularly in Java, and know it like the back of your hand, or whether you’re new to the language or a casual programmer, you’ll make mistakes. The purpose of this webinar is to talk about some Do's and Don'ts of Java programming.
The webinar will cover the following areas:
- Top 10 mistakes made by Java programmers – How to avoid them
- Core Java- Best Practices – This covers good and bad practices both
- How to prepare for Java Interviews and Sun Java Exams
- Q&A
Key learnings from this webinar:
- It will benefit both junior and senior java professionals so that they don’t make common errors
- Clarity of concepts of Java
- Better awareness of best practices of Java
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
Whether you program regularly in Java, and know it like the back of your hand, or whether you’re new to the language or a casual programmer, you’ll make mistakes. The purpose of this webinar is to talk about some Do's and Don'ts of Java programming.
The webinar will cover the following areas:
- Top 10 mistakes made by Java programmers – How to avoid them
- Core Java- Best Practices – This covers good and bad practices both
- How to prepare for Java Interviews and Sun Java Exams
- Q&A
Key learnings from this webinar:
- It will benefit both junior and senior java professionals so that they don’t make common errors
- Clarity of concepts of Java
- Better awareness of best practices of Java
A talk about how Javascript developers can make better and less error prone code by adopting two practices: using type-checkers to validate types during the development process, using Flowtype as an example; and by applying some common clean code practices to make their code more readable.
This document provides an overview and introduction to building a basic fraction calculator app in Objective-C. It begins with an overview of the project architecture using the MVC pattern with a Fraction model class to represent fractions, a Calculator class to perform operations, and a ViewController class to manage the user interface. It then details the implementation of each class, including the Fraction class with methods for creating, modifying, and performing operations on fractions, the Calculator class for setting operands and performing operations, and the ViewController class for handling user interface events and updating the display.
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
What do threads, atomic variables, mutexes, and conditional variables have in common? They are the basic building blocks of any concurrent application in C++, which are even for the experienced C++ programmers a big challenge. This massively changed with C++17 and change even more with C++20/23. What did we get with C++17, what can we hope for with C++20/23? With C++17, most of the standard template library algorithms are available in sequential, parallel, and vectorised variants. With the upcoming standards, we can look forward to executors, transactional memory, significantly improved futures and coroutines. To make it short. These are just the highlights from the concurrent and parallel perspective. Thus there is the hope that in the future C++ abstractions such as executors, transactional memory, futures and coroutines are used and that threads, atomic variables, mutexes and condition variables are just implementation details.
The document discusses C++ interview questions and answers related to classes, inheritance, pointers, references, and operator overloading. It provides code examples to demonstrate concepts like passing objects by value vs reference, virtual functions, and inheritance. The examples are tested on Turbo C++, Microsoft VC++ compilers under Windows environment on x86 systems.
The document discusses key concepts in Java including:
1) The javadoc program generates API documentation from source code comments. Classes contain data fields and methods and can have inner classes.
2) Objects have lifetimes separate from primitive variables and remain in memory until garbage collected. Static methods and fields exist independently of any object.
3) Arrays are objects that are dynamically allocated and indexed starting at 0. Arrays know their own length and certain operations are defined on arrays.
This document discusses how to use three C++17 vocabulary types: std::optional, std::variant, and std::any. It begins with an introduction and overview of the types. It then provides examples and explanations of how to create, access, and manipulate values for each type. Key points covered include initialization, accessing contained values, performance characteristics, and common use cases.
The document discusses switch case statements and looping in programming. It provides examples of switch case statements that allow a program to execute different code depending on the value of a variable. It also discusses the three main types of loops - for, while, and do while loops - and provides examples of how to write each type of loop. The document is intended to help explain switch case statements and looping to programmers.
This document provides an overview of the Java programming language including how it works, its features, syntax, and input/output capabilities. Java allows software to run on any device by compiling code to bytecode that runs on a virtual machine. It is object-oriented, supports features like inheritance and polymorphism, and has memory management and security benefits over other languages. The document also discusses Java concepts like classes, methods, arrays, and streams for file input/output.
This document provides an overview of the Java programming language including how it works, its features, syntax, and input/output capabilities. Java allows software to run on any device by compiling code to bytecode that runs on a virtual machine instead of a particular computer architecture. It is an object-oriented language with features like automatic memory management, cross-platform capabilities, and a robust class library.
The document discusses Java classes, methods, and constructors. It explains that classes define data objects and operations that can be applied to those objects. Methods and variables can be declared as static, existing independently of any object. Constructors are used to create instances of a class and automatically invoke the superclass constructor.
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
Revamped for 2011 (90% new material), this session will guide any level of programmer to greater productivity by providing the information needed to write consistent, maintainable code. Learn about project setup, assembly layout, code style, defensive programming and much, much more. Code tips are included to help you write better, error free applications. Lots of code examples in C# and VB.NET. This session is based off my latest book, David McCarter's .NET Coding Standards.
This document provides an overview of JavaScript development challenges and how EcmaScript 2015 and TypeScript address these challenges. It discusses the rise of JavaScript, traditional development challenges like lack of structuring capabilities and static types, new features in EcmaScript 2015 like arrow functions and classes, and how TypeScript adds static types and interfaces to provide benefits for large application development. The document contains code examples to demonstrate various JavaScript and TypeScript language features.
This document summarizes a talk given at YAPC Tokyo 2010 about calling C code from Perl using various techniques. It discusses Ctypes, a module for directly calling C functions without XS; Libperl++, a C++ library for embedding and extending Perl; and XS++, which allows writing C++ classes that integrate seamlessly with Perl using a special syntax.
1. CSE 380 C++ Boot Camp
Part 1/2
C++
You
Slides by Jesse Talavera-Greenberg
2. Disclaimer
I am not the grader for this course
Undergrads can't grade assignments
The boot camp is always part of the course,
but I volunteered to lead it this year
Any opinions expressed are my own and are
not necessarily condoned by McKenna
I don't know very much about DirectX
3. This Week
No need to download anything this week
Go to www.cppreference.com to follow code
This is your C++ Bible this semester
Online compiler
4. Basic Structure
#include <iostream>
// Include any header files at the top of the .cpp file to use the classes and
// functions they define
using std::cout;
using std::endl;
// Now do this to use names (or prefix them with “std::”)
// static initializers will be called before main()
// Main entry point of a C++ program
int main(int argc, char** argv, char** env) {
// All these args are optional, third one is not as common
// argc == number of command-line arguments
// argv == the actual arguments as an array of strings
// env == environment variables
cout << "Hello! The name of this program is " << argv[0] << endl;
// Call functions! Do things!
return 0;
// Return code of 0 tells the OS the program exited normally
// Anything else == something went wrong (you decide what the numbers mean)
// Leaving it off implies "return 0"
}
5. if, else, for, while
Ranged for available, too (we'll come back)
if (somethingIsTrue()) {
for (int i = 0; i < 10; ++i) {
break; // Exactly the same
}
}
else if (somethingElseIsTrue()) {
while (true) break;
// You can omit braces for single statements like in Java
}
else {
do {
continue; // Exactly the same
} while (false);
}
6. switch
●
Same, except cases can't be strings
switch (someInteger) { // All okay
case 0:
break;
case SOME_CONSTANT:
break;
default:
// nop
}
switch (someString) { // ERROR
case "No way":
case "Too bad":
case "Don't bother":
default:
// nop
}
7. try/catch/throw
There is no finally
Use destructors instead (we'll come back)
using std::exception;
try {
functionThatMightThrowException(); // No checked exceptions in C++
throw exception("No new statement; we'll come back to this");
}
catch (exception e) {
std::cout << e.what(); // Print the exception info
}
try {
throw 5;
// You can throw anything in C++
}
catch (int i) {
// Stick to exception objects and their subclasses, though
}
catch (...) {
// Catch anything, but you can't access it; can only be used last
}
8. Fundamental types
Sizes are not well-
defined like in Java
No byte (use
uint8_t)
boolean → bool
Use nullptr instead
of null or NULL
Signed and unsigned
types
signed types are the
same
unsigned types
double the max value,
but can't represent
negative numbers
Need a specific number size?
First #include <cstdint>
Then use std::u?int(8|16|32|64)_t
9. typedef and typeid
#include <cstdint>
#include <iostream>
#include <typeinfo>
// ^ Must include typeinfo to use the typeid operator
typedef std::uint8_t byte;
// Declares another name for the same type
// Syntax:
// typedef existing_type new_name;
using std::cout;
using std::endl;
int main() {
std::uint8_t a = 5;
byte b = a; // Totally okay; the distinction is compile-time only
cout << typeid(std::uint8_t).name() << endl;
cout << typeid(byte).name() << endl;
// Both printouts will be implementation-defined, but identical
/*
Common standard typedefs:
size_t: Sizes of objects (usually an unsigned int)
ptrdiff_t: Difference between pointers (usually an unsigned int or long)
std::string: Convenient form of std::basic_string<char>
*/
}
10. Declaring Variables
#include <string>
#include <vector>
using std::string;
using std::vector;
int main() {
string empty; // default constructor
string empty2(); // default constructor with parens
string value = "I'm really a char*";
string value2("Parens are fine, too");
string copy = value; // This is a COPY; NOT A REFERENCE
string& ref = value; // THIS is a reference
const string& constref = value; // A reference whose object can't be modified
// All of an object's members are initialized!
string* ptr; // Unassigned pointer; not necessarily nullptr
vector<int> ints = {1, 2, 3, 4, 5, 6}; // You can initialize collections this way
}
11. Undefined behavior
Whenever something happens in Java, you can
rely on something else to happen
C++ lets the compiler do anything it wants in
certain situations
For performance reasons, mostly
Many, many ways to do this
Do not rely on undefined behavior
12. Common undefined
behaviors
#include <string>
#include <cstdint>
#include <limits>
int32_t something(int32_t param) {
if (param > 0) return param;
// No return down here; now what?
}
std::string& returnsALocal() {
std::string reference = "Why are you doing this";
return reference; // Uh-oh
}
int main() {
int32_t a = std::numeric_limits<int32_t>::max();
a++; // Oops
int32_t* pointer; // Could be nullptr, could be garbage
int32_t number = *pointer; // BAD
int32_t[10] array;
number = array[12]; // WTF
}
13. namespace
#include <iostream>
#include <string>
#include <array>
#include <utility>
using namespace std;
// ^ Don't do this for the same reason you don't do java.util.*
namespace sbcs {
// Nest them as much as you'd like
namespace cse380 {
struct Game {
string name;
string teamName;
array<string, 3> members;
};
}
namespace cse381 {
typedef pair<string, string> Team;
}
}
int main() {
sbcs::cse380::Game game; // Fully-qualified type name
using sbcs::cse381::Team; // Or use it in the current namespace (global in this case)
Team team("Jesse", "Karl");
}
14. The Preprocessor
#include <iostream>
// Use <angle_brackets> for standard library/third-party code, "quotes" for your own
#define DEBUG
// You can also add #defines through your build system (e.g. the command line or
// your Visual Studio project file)
// #define WINDOWS
// #define MAC
// ^ Uncomment one of these
using std::cout;
using std::endl;
int main() {
#ifdef DEBUG
cout << "Logging! Or sanity checking!" << endl;
#endif
#ifdef WINDOWS
cout << "Use DirectX!" << endl;
#else
cout << "Use OpenGL!" << endl;
#endif
#ifdef MAC
#error "Jesse doesn't like Apple"
// ^ Intentionally causes a compiler error
#endif
}
15. assert/static_assert
#include <cassert>
#include <type_traits>
// #define NDEBUG
// ^ Uncomment this or define it in the build system to disable asserts
using std::is_base_of;
using std::is_same;
template<class T, class U>
void failIfUnrelated() {
static_assert(
is_base_of<T, U>::value
|| is_base_of<U, T>::value
|| is_same<T, U>::value,
"Both types should be the same, or one should be a parent of the other"
);
}
class Parent {};
class Child : public Parent {};
int main() {
assert(1 + 1 == 2);
assert(true && "Idiom for providing informative text in an assert()");
failIfUnrelated<int, int>(); // Okay
failIfUnrelated<int, float>(); // Causes a compiler error, as desired
failIfUnrelated<Parent, Child>(); // Okay
}
16. enum
#include <iostream>
using std::cout;
using std::endl;
enum class Direction {
North,
South,
East,
West, // Trailing comma is okay
};
// NOT OBJECTS; just ints with some compile-time meaning
enum class Speakers {
Mute = 0, // Assigning values is okay
Mono = 1,
Stereo = 2,
Surround = 4
};
int main() {
Direction dir = Direction::North;
Speakers audio = Speakers::Stereo;
audio = Speakers(4); // Make sure int is a valid Speakers value!
cout << int(audio) << endl;
// int <-> enum class conversions must be explicit
}
17. Pointers
#include <string>
using std::string;
int main() {
string a = "I'm a little teapot";
string* ptr = &a; // &some_object returns the address of some_object
string b = *ptr; // *some_pointer dereferences
int ints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Raw arrays are pointers
int* int_ptr = ints; // Points to ints[0]
int* int_ptr2 = ints + 1; // Points to ints[1]
// Increments the address sizeof(int) bytes
int** double_array = &int_ptr;
// Pointers to pointers okay; never usually need more than two**
void* pointer_to_anything = ints;
// Pointer to arbitrary data; very error-prone and unsafe; avoid unless you know
// exactly why you need one
pointer_to_anything = nullptr;
// nullptr == Java's null; assignable to any pointer type, but not to objects
float* garbage; // Uninitialized pointer; value is undefined
// Could be garbage, could be nullptr; initialize it ASAP!
}
18. References
#include <string>
#include <iostream>
using namespace std; // Only for slide space constraints
class StringHolder {
public:
StringHolder(const string& str) : _str(str) {}
const string& getStringReference() const { return this->_str; }
string getStringCopy() const { return this->_str; }
void append(const string& str) { this->_str += str; }
// ^ Passes an unmodifiable reference rather than a copy
private:
string _str;
};
int main() {
StringHolder holder("France");
const string& a = holder.getStringReference();
string b = holder.getStringCopy();
cout << (a == b) << endl; // True; comparing object values
cout << (&a == &b) << endl; // False; different addresses, different objects
holder.append(b);
cout << holder.getStringReference() << endl; // FranceFrance
}
19. Pointers Vs. References
(Similarities)
Access large objects without copying them
Left dangling (invalid) if the referenced object
is deallocated
No way to check for this
Will likely cause a crash if you try to use it
Both can point to an instance of the given type's
superclass
Both compiled to similar machine code
Multiple pointers/references can refer to one
object
20. Pointers Vs. References
(Differences)
Can represent
absence of data
More prone to
becoming invalid
Syntax needed to
convert between
pointers and objects
Can be assigned to
different objects
Always initialized with
a valid object
No syntax needed to
use references aside
from declarations or
method signatures
Always points to one
location in memory
Easier to deal with
objects that shouldn't
change
21. new/delete
#include <string>
using std::string;
void wasteMemory() {
string stack_allocated = "I disappear when I go out of scope";
string* wasted = new string(
"I only disappear when explicitly deallocated"
);
string* cleaned = new string("I'm about to get cleaned up properly");
delete cleaned;
}
int main() {
for (int i = 0; i < 10000; i++) {
wasteMemory();
}
// stack_allocated disappeared when wasteMemory() returned
// All instances of wasted are still in memory
// cleaned disappeared when "delete cleaned;" was called
// See: Scope vs. Lifetime
}
22. Exceptions
#include <iostream>
#include <string>
#include <exception>
#include <array>
using namespace std; // Again, slide space constraints
int main() {
array<int, 5> ints = {1, 2, 3, 4, 5};
try {
cout << ints.at(10) << endl; // at() checks bounds, operator[] doesn't
}
catch (const out_of_range& e) { // You can (and should) catch by reference
cout << "Out of range in an array" << endl;
}
catch (const runtime_error& e) {
cout << "Didn't see this coming: " << e.what() << endl;
}
catch (const exception& e) {
cout << "Unknown exception: " << e.what() << endl;
}
catch (...) {
cout << "WTF?" << endl;
}
// There is no finally clause; use destructors to guarantee exception safety
}
23. Declaring Classes
// public/protected/private semantics same as in Java
// no specifier == private in classes, public in structs
class ItHoldsThings {
public:
int cantBeOverridden(int a, int b) {
// Technically you can, but things get weird
return this->_integer + b;
}
virtual float canBeOverridden(const double d) {
// virtual == overrideable
return d * 2;
}
virtual void abstractMethod() = 0;
protected:
float _number;
private:
int _integer;
}; // Don't forget the semicolon
// When a class is constructed, ALL of its members are too
24. Constructors
#include <string>
using std::string;
class StringWrapper {
public:
StringWrapper() { /* other code here */ } // _str == ""
// Default constructor can be auto-generated with some caveats (see the wiki)
StringWrapper(const string& value) : _str(value) {} // _str == value
// Copy constructor can be auto-generated (but see wiki)
// Base class constructors are called like this, too
private:
string _str;
// All members are initialized on construction, whether you like it or not
};
int main() {
StringWrapper a;
StringWrapper b("There will be a copy of me in c");
StringWrapper c(b);
}
25. // Using constructors to allocate resources and destructors to clean them up is
// called Resource Acquisition Is Initialization (RAII). Only needed for low-level
// resources; high-level classes like std::iostream do RAII themselves.
#include <cstdlib>
using std::malloc;
using std::free;
class LotsOfResources {
public:
LotsOfResources() {
_floats = new float[64];
_buffer = malloc(64);
}
~LotsOfResources() { // Called when this object's lifetime ends
delete[] _floats; // Remember the [] when deleting a raw array
free(_buffer);
}
private:
float* _floats;
void* _buffer;
};
int main() {
LotsOfResources* resources = new LotsOfResources;
delete resources; // No memory leaks!
}
Destructors
26. Abstract Classes/Inheritance
#include <exception>
#include <iostream>
// There are no interfaces; use abstract classes without any concrete methods
struct ProgramCrasher {
virtual void crash() = 0; // "= 0" means the method is abstract
// virtual == method can be overridden
// only one abstract method needed to define a class as abstract
};
struct IPastryChef {
virtual void bake() = 0;
};
struct SegfaultCrasher : public ProgramCrasher {
// Actually several types of inheritance; it's complicated, just use public
void crash() override {
int* a;
int b = *a;
}
};
// Multiple inheritance; don't do it if more than one parent class is not an interface
struct ExceptionCrasher : public ProgramCrasher, public IPastryChef {
void crash() override { throw std::exception(); }
void bake() override {
std::cout << "This is just my day jobn";
}
};
27. (static|dynamic)_cast
#include <iostream>
#include <string>
using namespace std; // Slide space constraints
struct Base {
virtual ~Base() {}
string baseMethod() { return "base"; }
};
struct Derived: Base {
virtual string derivedMethod() { return "derived"; }
};
int main()
{
Base* b1 = new Derived;
Derived* d1_s = dynamic_cast<Derived*>(b1);
cout << d1_s << ' ' << d1_s->baseMethod() << ' ' << d1_s->derivedMethod() << endl;
// Checking at runtime that you're casting to the right type
Derived* d1_d = static_cast<Derived*>(b1);
cout << d1_d << ' ' << d1_d->baseMethod() << ' ' << d1_d->derivedMethod() << endl;
// Static (compile-time) downcasts are OK (and faster) if you know you're
// casting to the right type
Base* b2 = new Base;
Derived* d2_d = dynamic_cast<Derived*>(b2);
cout << d2_d << endl;
// Cast was not valid, so dynamic_cast returned nullptr
// If it were a reference, it would've thrown std::bad_cast
Derived* d2_s = static_cast<Derived*>(b2);
// cout << d2_s << ' ' << d2_s->baseMethod() << ' ' << d2_s->derivedMethod() << endl;
// ^ This is undefined, since the cast is wrong (and not checked at runtime)
delete b1; // Remember to clean up!
delete b2;
}
28. Templates
#include <string>
#include <vector>
template<class T>
class Value {
public:
Value(const T& data) : _data(data) {}
const T& getData() { return this->_data; }
private:
T _data;
};
// Templates are used A LOT in the standard library
using std::string;
using std::vector;
int main() {
Value<string> str("My name is Beavis");
Value<vector<int>> ints({1, 2, 3, 4, 5, 6});
// Two different classes, with two different bits of machine code
}
29. Templates
#include <iostream>
#include <array>
#include <vector>
#include <string>
using namespace std; // Slide space constraints
template<class T>
void printIt(const T& object) {
cout << object << endl;
}
template<class Container>
void needsABeginMethod(Container& container) {
auto iterator = container.begin();
// The begin() method returns an iterator
}
int main() {
printIt(42); // Type parameters in function templates are usually inferred
printIt<float>(7.3); // You can specify them explicitly if you need to
array<int, 3> ints = {1, 2, 3};
vector<int> vec = {5, 6, 7, 8, 9};
string str = "Strings are containers";
needsABeginMethod(ints);
needsABeginMethod(vec);
needsABeginMethod(str);
// needsABeginMethod(47); ERROR: ints don't have such a method
}
30. Templates
#include <array>
#include <iostream>
#include <typeinfo>
#include <string>
using namespace std; // slide space limits
template<class T, int ArrayLength = 10>
class SomeTypedefs {
public:
SomeTypedefs() = delete; // Prevent instantiation
typedef T Type;
typedef T* Pointer;
typedef T& Reference;
typedef T RawArray[ArrayLength];
typedef array<T, ArrayLength> STLArray;
};
// The standard library does this a lot ^
int main() {
cout << typeid(SomeTypedefs<int>::Type).name() << endl;
cout << typeid(SomeTypedefs<float>::Pointer).name() << endl;
cout << typeid(SomeTypedefs<string>::Reference).name() << endl;
cout << typeid(SomeTypedefs<int, 14>::RawArray).name() << endl;
cout << typeid(SomeTypedefs<double, 3>::STLArray).name() << endl;
}
31. const
#include <string>
using std::string;
const int SOME_CONSTANT = 34;
const string ANOTHER_CONSTANT = "More type-safe than macros!";
class ConstStuff {
public:
int getData() const { // The method doesn't modify the object
return this->_data;
}
const string& getText() const {
// Gives you an immutable reference to _text; you must assign it to
// a const std::string& if you don't want to copy it
return this->_text;
}
void concatenate(const string& str) {
// str itself can't be modified, and it's not copied
this->_text += str;
}
private:
int _data;
string _text;
};
// Attempting to violate const-correctness through runtime tricks is UB
32. Operator Overloading
#include <iostream>
using std::cout;
using std::endl;
using std::ostream; // cout is an ostream
struct Vector2 {
float x, y;
Vector2(const float x, const float y) : x(x), y(y) {}
Vector2 operator+(const Vector2& other) {
return Vector2(x + other.x, y + other.y);
}
};
// This is how most types in the standard library are printed out
ostream& operator<<(ostream& out, const Vector2& v){
return out << '[' << v.x << ", " << v.y << ']';
}
int main() {
Vector2 a(1, 2);
Vector2 b(2, 1);
Vector2 c = a + b;
cout << c << endl;
}
33. Strings to numbers and back
#include <string>
#include <cstdlib>
using std::string;
using std::stoi;
using std::stol;
using std::stoll;
using std::size_t;
// sto(i|u?ll?|f|l?d) is available
using std::to_string; // to_wstring is available too
int main() {
int a = stoi("42");
// a == 42
long b = stol(" 0x09", nullptr, 16); // Strips whitespace, reads as base 16
// b == 9
size_t first_nonnumeric_char_index;
long long c = stoll("12lbs", &first_nonnumeric_char_index, 0);
// c == 12, first_nonnumeric_char_index == 2
// base-0 means assume either base 8, 10, or 16 depending on the prefix
string back = to_string(c); // 12
}
35. Random numbers
#include <iostream>
#include <random>
using std::cout;
using std::default_random_engine;
using std::endl;
using std::normal_distribution;
using std::random_device;
int main()
{
random_device seed;
default_random_engine random(seed());
// Seed the generator with a totally random number (as opposed to
// something like the system time)
normal_distribution<float> normal(0, 1); // mean == 0, stddev == 1
for (int i = 0; i < 100; ++i) {
cout << normal(random) << ' ';
// Use seed instead of random if you REALLY want randomness
// (but that will be slower)
}
cout << endl;
}
36. String Concatenation
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
using std::setprecision;
int main()
{
float x = 5.6435221, y = 7.1453634545, z = -23.452354215;
stringstream coords;
coords << "DEBUG LOGn"
<< "tPosition: [" << setprecision(4)
<< x << ", " << y << ", " << z << "]n";
cout << coords.str() << endl;
// Use stringstream for formatted output like in debug consoles
// Small amounts of pre-existing strings can be appended with operator+
}
37. Iterators
#include <array>
#include <string>
#include <iostream>
using std::array;
using std::cout;
using std::endl;
using std::string;
int main() {
array<string, 5> strings = {"France", "Spain", "China", "America", "Sweden"};
// No iterators
for (int i = 0; i < strings.size(); i++) {
cout << strings[i] << ' ';
}
cout << endl;
// The clunky way
for (array<string, 5>::iterator it = strings.begin(); it != strings.end(); it++) {
cout << *it << ' ';
}
cout << endl;
// The C++11 way
for (const string& s : strings) {
cout << s << ' ';
}
cout << endl;
}
38. Anonymous Functions and
<algorithm>
#include <array>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std; // For slide space
int main() {
array<int, 10> ints = {5, 7, 1, 2, 3, 9, 2, 1, 4, 2};
function<bool(int)> isEven = [](int n) -> bool {
return n % 2 == 0;
};
// () can be omitted if there are no parameters
function<void(void)> printInts = [&ints] {
for (int i : ints) {
cout << i << ' ';
}
cout << endl;
};
printInts();
// return type can be omitted if it can be deduced
transform(ints.begin(), ints.end(), ints.begin(), [&isEven](int i) {
// [&something] captures something by reference, [something] by value
return isEven(i) ? i : i * 2;
}); // ^ Doubles all odd numbers
printInts();
}
39. Time
#include <chrono>
#include <iostream>
#include <thread>
using std::cout;
using std::endl;
using std::this_thread::sleep_for;
using std::chrono::duration;
using std::chrono::duration_cast;
using std::chrono::system_clock;
typedef duration<float> secondsf; // Seconds, represented as a float
// Standard typedefs for seconds, milliseconds, hours, etc. exist, too
const int FPS = 60;
int main() {
secondsf ms_per_frame(1.0 / FPS);
system_clock::time_point start = system_clock::now();
for (int i = 0; i < 300; i++) {
sleep_for(ms_per_frame);
cout << "Frame #" << i << endl;
}
cout << "Elapsed time: "
<< duration_cast<secondsf>(system_clock::now() - start).count()
<< " secondsn";
}
40. Next Week
Compiling and linking code
Using Visual Studio
Overview of popular C++ tools
Building and using Box2D
This is part of your homework!